Exceptions are events that occur during the execution of a program and alter the normal flow of instructions.
In Python, when an error occurs, an exception is raised. This is an object that symbolizes the error and contains information about it.
This exception can,
- Be caught by a
try
block - If not, it passes to the function that invoked the one that generated the error.
Thus, the exception goes “up”. If no one handles it, the exception will reach the main function, and normally the program will terminate abruptly.
The Try-Except Block
Exceptions in Python are managed 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. Within this block, the code that you want to execute and that could raise 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 the exceptions that occur within the try
block.
Within this block, the code that you want to execute in case an exception occurs is placed.
For example,
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,
- Within the
try
block we have the operation10/0
, which will cause an error (because division by zero is not possible). So an exception will be raised. - The
except
block will capture 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 simply using 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.")
The 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("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.")
The 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.")
Within this block, the code that 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.