Python try except finally
The try-except-finally block is a construct in Python used for handling exceptions and executing cleanup code.
The basic syntax of a try-except-finally block is:
try:
# code that may raise an exception
except ExceptionType1 as e1:
# code to handle exception type e1
except ExceptionType2 as e2:
# code to handle exception type e2
finally:
# code to be executed regardless of whether an exception occurred or not
In this block:
- The
try
block contains the code that may raise an exception. - If an exception is raised, it will be caught by the appropriate
except
block based on the exception type. You can have multiple except blocks for handling different types of exceptions. - The
finally
block is optional and contains code that will always be executed, regardless of whether an exception occurred or not. This is typically used for cleanup operations such as closing files or releasing resources.
Here's an example:
try:
x = 10 / 0 # raises ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This will always be executed")
# Output:
# Cannot divide by zero
# This will always be executed
Note that if there is no exception raised, the except block(s) will be skipped and only the finally block will be executed.