Exception Handling with Try-Catch in Python with Examples

Python Python Basics

Exception handling in Python is an essential part of programming that allows developers to anticipate, detect, and recover from errors or exceptions that may occur during the execution of a program. In this article, we will explore exception handling using the try-catch mechanism in Python, one of the most popular high-level programming languages.

Table of Contents


Python provides built-in support for exception handling through the try, except, and finally keywords. These keywords help developers to create a block of code that can be executed without worrying about errors or exceptions occurring within it. In this section, we will provide some basic examples to understand how exception handling works in Python.

The try-catch Block

The try block is used to enclose the lines of code that may potentially raise an exception. When an error occurs within a try block, its execution stops, and control is passed to the except or finally blocks (if present). Here’s an example:

# Example 1 - Handling ZeroDivisionError
    result = 5 / 0
except ZeroDivisionError as e:
    print("An error occurred:", str(e))
    print("Result is:", result)

In this example, we attempt to divide 5 by 0, which will raise a ZeroDivisionError. The except block catches the exception and prints an informative message about it. If no error occurs within the try block, the else block (if present) is executed.

Multiple Exception Handling

Sometimes, we need to handle multiple exceptions in our Python code. Python allows us to do this by listing all the possible exception types within a single except block:

# Example 2 - Handling Multiple Exceptions
    # Some code that may raise an exception
    result = int("abc")
except (ValueError, TypeError) as e:
    print(f"An error occurred: {e}")

In this example, we attempt to convert a string containing non-numeric characters into an integer. This will raise either ValueError or TypeError. The except block catches both exceptions and prints the appropriate error message.

Exception Chaining

Python allows us to chain multiple exceptions within a single except block, making it easier to handle complex scenarios:

# Example 3 - Handling Exception Chaining
    # Some code that may raise an exception
    with open("non_existing_file.txt", "r") as f:
        content = f.read()
except FileNotFoundError as e:
    raise IOError("IOError") from e

In this example, we attempt to open a non-existing file for reading. This will raise either FileNotFoundError. The except block catches the exception and raises a new exception IOError.

Exception Hierarchy

Python follows an exception hierarchy where some exceptions are subclasses of other exceptions. In such cases, we can catch a more general exception type to handle its subtypes as well:

# Example 4 - Handling Exception Hierarchy
    # Some code that may raise an exception
    result = int("abc")
except Exception as e:
    print(f"An error occurred: {e}")

In this example, we catch the most general Exception type to handle any exception raised by our code. This includes all subclasses of Exception, such as ValueError and TypeError.

The finally Block

The finally block is executed regardless of whether or not an exception occurs within the try block. It’s useful for cleaning up resources, like closing open files or database connections:

# Example 5 - Using finally Block to Close Resources
    # Some code that may raise an exception
    with open("existing_file.txt", "r") as f:
        content = f.read()
except (FileNotFoundError, IOError) as e:
    print(f"An error occurred: {e}")
    # Close the file here, even if an exception occurs
    print("Finally block") # Output: Finally block

In this example, we open a file for reading and handle any potential exceptions. The finally block makes sure that the file is closed regardless of whether an error occurred or not.


Exception handling in Python using the try-catch mechanism allows developers to create robust and reliable programs by anticipating and recovering from errors. By understanding the various aspects of exception handling, such as multiple exceptions, exception hierarchy, and resource management with the finally block, we can write more resilient code that provides better user experiences.

To top