Exception handling
Exception handling is a programming construct that allows you to detect, manage, and respond to
unexpected events, or exceptions, that occur during a program's execution. Instead of crashing, a
program can use exception handling to manage these problems smoothly, making the software
more reliable and user-friendly.
How exceptions work
When an exception occurs, the normal flow of the program is interrupted. Python, for example,
generates an "exception object" that contains information about the error. If this object is not
managed, the program will terminate abruptly and display a traceback error. Exception handling
allows a developer to catch and handle this exception object to prevent the program from
crashing.
The try-except-finally block
In Python, the try, except, and finally blocks are the primary tools for exception handling. They
work together to test code for errors, handle them if they occur, and perform cleanup actions
afterward.
The try block
The try block contains the code that might raise an exception.
• The interpreter executes the code inside the try block.
• If no exception occurs, the except block is skipped.
• If an exception occurs, the program stops executing the rest of the try block and
immediately jumps to the appropriate except block.
The except block
The except block contains the code that handles the exception.
• It catches a specific type of exception that occurred in the try block.
• You can have multiple except blocks to handle different types of exceptions in different
ways.
• By handling the error, you prevent the program from crashing and can provide a more
helpful message to the user.
The finally block
The finally block contains code that will always be executed, regardless of whether an exception
occurred or not.
• This block is typically used for essential cleanup actions, such as closing files or network
connections, to ensure resources are released properly.
• The finally block will execute even if an unhandled exception or a return statement is
present in the try or except blocks.
Example of try-except-finally
The following Python code demonstrates the use of all three blocks:
try:
# This code may raise an exception
result = 10 / 0
except ZeroDivisionError:
# This block executes if a ZeroDivisionError occurs
print("Error: You cannot divide by zero.")
except ValueError:
# This block would handle a different error, like converting an invalid number
print("Error: Invalid number format.")
finally:
# This block always executes, for cleanup
print("Execution complete. All resources have been managed.")
Use code with caution.
Output:
Error: You cannot divide by zero.
Execution complete. All resources have been managed.
In this example, the try block fails due to a ZeroDivisionError. The program immediately jumps to
the except ZeroDivisionError block, prints the specific error message, and then proceeds to
the finally block. The program finishes gracefully instead of crashing.