Language: EN

python-try-except

Catching Exceptions with Try-Except in Python

In Python, when an error occurs, an exception is raised. Exceptions are objects that symbolize the error and contain information about it.

Exceptions are events that occur during the execution of a program and that alter the normal flow of instructions.

This exception can,

  • Be caught by a try block
  • If not, it passes to the function that called the one that generated the error.

Thus, the exception goes “up”. If no one handles it, the exception will reach the main function and the normal behavior is that the program will terminate abruptly.

The Try-Except Block

Exceptions in Python are handled with a Try-Except block, which has the following basic syntax,

try:
    # Code that may raise an exception
    
except:
    # Code to execute if an exception occurs   

The try block is used to encapsulate the code that may generate an exception. Inside this block, the code that you want to execute and that could throw an exception is placed.

If no exception occurs, the program flow continues normally. If an exception occurs, the program flow is diverted to the except block.

The except block is used to capture and handle exceptions that occur within the try block. Inside this block, the code that you want to execute in case an exception occurs is placed.

try:
    # Code that may raise an exception
    result = 10 / 0
except:
    # Code to execute if an exception occurs
    print("An exception occurred.")

In this case,

  • Inside the try block, we have the operation 10/0, which will result in an error (because division by zero is not possible). So it will raise an exception.
  • The except block will catch the exception and display the text “An exception occurred.”

Capturing Multiple Exceptions

It is possible to capture specific exceptions using the syntax except ExceptionType or capture any type of exception using simply except:.

try:
    # Code that may raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # Code to execute if a ZeroDivisionError occurs
    print("Cannot divide by zero.")
except ValueError:
    # Code to execute if a ValueError occurs
    print("Incorrect value.")
except:
    # Code to execute if any type of exception occurs
    print("An exception occurred.")

else Block

The else block is used to execute code if no exception occurs in the try block.

try:
    # Code that may raise an exception
    result = 10 / 2
except ZeroDivisionError:
    # Code to execute if a ZeroDivisionError occurs
    print("Cannot divide by zero.")
else:
    # Code to execute if no exception occurs
    print("The division was successful. The result is:", result)
finally:
    # Code to execute always, regardless of whether an exception occurs or not
    print("This line will always execute.")

finally Block

The finally block is used to execute code regardless of whether an exception occurs or not.

try:
    # Code that may raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # Code to execute if a ZeroDivisionError occurs
    print("Cannot divide by zero.")
finally:
    # Code to execute always, regardless of whether an exception occurs or not
    print("This line will always execute.")

Inside this block, the code you want to execute always is placed, for example, to free resources or perform some cleanup.

Exception Handler Context

The try, except, else, and finally blocks share context. The variables we create in the try block will be available in the rest. For example,

try:
    file = open('file.txt', 'r')
    content = file.read()
except FileNotFoundError:
    print("The file was not found.")
except IOError:
    print("Error reading the file.")
else:
    print("The file was read successfully. Content:")
    print(content)
finally:
    if 'file' in locals() and not file.closed:
        file.close()
        print("The file has been closed.")

In this case, file and content are available in the else and finally blocks, even though they were defined in the try block.