Exception Handling in Python

In Python, exceptions are used to handle errors and unexpected situations that may occur during the execution of a program. Exception handling allows us to gracefully handle these situations and prevent the program from crashing.

The try-except Block

The basic structure for exception handling in Python is the try-except block. The try block contains the code that may raise an exception, while the except block contains the code that will be executed if an exception is raised. Here’s an example:

try:
    # code that may raise an exception
    x = 10 / 0
except ZeroDivisionError:
    # code to handle the exception
    print("Division by zero!")

In this example, the try block contains the code that may raise a ZeroDivisionError. If an exception is raised, the except block is executed, and the message “Division by zero!” is printed.

Multiple except blocks can be used to handle different types of exceptions:

try:
    # code that may raise an exception
    x = int("abc")
except ValueError:
    # code to handle the ValueError exception
    print("Invalid value!")
except ZeroDivisionError:
    # code to handle the ZeroDivisionError exception
    print("Division by zero!")

In this example, the try block contains the code that may raise a ValueError or a ZeroDivisionError. If a ValueError is raised, the first except block is executed and the message “Invalid value!” is printed. If a ZeroDivisionError is raised, the second except block is executed and the message “Division by zero!” is printed.

The finally Block

The finally block is used to execute code that should always be run, regardless of whether an exception is raised or not. The finally block is placed after all the except blocks. Here’s an example:

try:
    # code that may raise an exception
    f = open("file.txt", "r")
    print(f.read())
except IOError:
    # code to handle the IOError exception
    print("Unable to open file!")
finally:
    # code to close the file
    f.close()

In this example, the try block contains the code that may raise an IOError. If an IOError is raised, the first except block is executed and the message “Unable to open file!” is printed. The finally block is always executed, and is used to close the file that was opened in the try block.

Raising Exceptions

Exceptions can also be raised manually using the raise statement. Here’s an example:

try:
    # code that may raise an exception
    x = -1
    if x < 0:
        raise ValueError("Invalid value!")
except ValueError as e:
    # code to handle the ValueError exception
    print(e)

In this example, the try block contains the code that may raise a ValueError. If x is less than 0, a ValueError is raised manually using the raise statement. The except block is executed, and the message “Invalid value!” is printed.

In summary, exception handling in Python allows us to gracefully handle errors and unexpected situations that may occur during the execution of a program. The try-except block is used to catch and handle exceptions, and the finally block is used to execute code that should always be run. Exceptions can also be raised manually using the raise statement.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *