Skip to main content

2.6 - Exception Handling

Exception handling is a crucial aspect of programming that allows you to handle and respond to errors and exceptional situations in a controlled manner. Python provides a powerful mechanism for exception handling, which helps in writing robust and error-tolerant code. In this guide, we will explore the fundamentals of exception handling in Python, including definitions, code examples, tables, and summaries.

2.6.1 - Introduction to Exceptions

Exceptions are events or errors that occur during the execution of a program, which disrupt the normal flow of the program. When an exception occurs, Python generates an exception object that contains information about the error. Exception handling allows you to catch and handle these exceptions, preventing the program from crashing.

In Python, exceptions are represented by classes. When an exception occurs, an instance of the corresponding exception class is created and raised. The raised exception is then caught by an exception handler that processes it appropriately.


2.6.2 - Try-Except Block

The try-except block is used to handle exceptions in Python. It allows you to enclose a section of code that might raise an exception within the try block, and specify how to handle the exception in the corresponding except block.

Here's the syntax of a basic try-except block:

try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception

The try block contains the code that you want to monitor for exceptions. If an exception occurs within the try block, the code execution is immediately transferred to the except block.

Let's consider an example to illustrate the usage of a try-except block:

try:
x = 10 / 0 # This division will raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero!")

In this example, the code inside the try block attempts to perform a division by zero, which raises a ZeroDivisionError. The except block catches the exception and prints an error message.


2.6.3 - Handling Multiple Exceptions

Python allows you to handle multiple exceptions using multiple except clauses. Each except clause can handle a specific type of exception.

Here's an example that demonstrates handling multiple exceptions:

try:
# Code that might raise an exception
except ExceptionType1:
# Code to handle ExceptionType1
except ExceptionType2:
# Code to handle ExceptionType2

In this example, if an exception of ExceptionType1 occurs, the first except block is executed. If an exception of ExceptionType2 occurs, the second except block is executed. You can have as many except blocks as necessary to handle different types of exceptions.


2.6.4 - The Finally Block

The finally block is used to define code that should be executed regardless of whether an exception occurred or not. The statements in the finally block are executed even if an exception is raised and not caught by any except block.

The finally block is typically used for cleanup tasks such as closing files or releasing resources.

Here's an example that demonstrates the usage of the finally block:

try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
finally:
# Code to be executed regardless of exceptions

In this example, the code inside the try block is executed first. If an exception occurs, the corresponding except block is executed. Finally, the code inside the finally block is executed.


2.6.5 - Raising Exceptions

Python allows you to manually raise exceptions using the raise statement. You can raise a specific exception type or create a custom exception by subclassing the built-in exception classes.

Here's an example that demonstrates raising an exception:

def divide(x, y):
if y == 0:
raise ZeroDivisionError("Division by zero is not allowed.")
return x / y

In this example, the divide function raises a ZeroDivisionError if the second argument y is zero.


2.6.6 - Built-in Exception Types

Python provides a variety of built-in exception types to handle different types of errors. These exceptions can be caught and handled using the appropriate except block. Some commonly used built-in exceptions include:

ExceptionDescription
ExceptionBase class for all exceptions
ZeroDivisionErrorRaised when division or modulo by zero is performed
TypeErrorRaised when an operation or function is applied to an object of inappropriate type
ValueErrorRaised when a function receives an argument of the correct type but an invalid value
FileNotFoundErrorRaised when a file or directory is requested but cannot be found
KeyErrorRaised when a dictionary key is not found
IndexErrorRaised when a sequence subscript is out of range

Refer to the Python documentation for a complete list of built-in exception types.