Junior
How does the use of multiple except blocks in Python work?
sobes.tech AI
Answer from AI
Allows handling of various types of exceptions that occur within a try block. Exceptions are checked sequentially — from the top except block to the bottom. The first except whose exception type matches or is a base class of the raised exception will be executed. The remaining except blocks are ignored.
try:
# Attempt to execute potentially erroneous code
result = 10 / 0 # Will raise ZeroDivisionError
my_list = [1, 2]
print(my_list[3]) # Will raise IndexError
except ZeroDivisionError:
# Handle division by zero
print("Error: Division by zero")
except IndexError:
# Handle index out of range
print("Error: List index out of range")
except Exception as e:
# Handle any other exceptions (general case)
print(f"An error occurred: {e}")
finally:
# This block always executes, regardless of whether an exception occurred or not
print("Finally block executed")
In this example, if a ZeroDivisionError occurs, only the first except block will execute. If an IndexError occurs, the second except block will execute. If an exception of another type occurs, the third except block (for the general case) will execute. The finally block will execute in any case. It is important to place more specific except blocks above more general ones to ensure correct exception handling.