Multiple except and finally
Sometimes code can fail in more than one way. You can write a separate except block for each kind of error, so each one gets its own response.
values = [10, 20]
position = "four"
try:
index = int(position)
print(values[index])
except ValueError:
print("Position must be a number")
except IndexError:
print("Position is outside the list")
finally:
print("Lookup finished")
Output:
Position must be a number
Lookup finished
int("four") raises ValueError, so Python runs the ValueError block and skips the IndexError block. Only the first except block that matches runs.
The finally block always runs. It runs when the try block succeeds, when an error is handled, and even when an error is not caught at all. Use it for cleanup work that must happen every time.
In the exercise, complete both except blocks and the closing message.