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
tryblock - 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 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 code that may generate an exception. Inside this block, you place the code you want to execute that could raise an exception.
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 catch and handle exceptions that occur within the try block. Inside this block, you place the code you want to execute in case an exception occurs.
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
tryblock we have the operation10/0, which will cause an error (because you cannot divide by zero). So an exception will be raised. - The
exceptblock will catch the exception and display the text “An exception occurred.” on the screen.
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("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.")
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.")
Inside this block, you place code that you want to always execute, for example, to release resources or perform some cleanup.
