Different failures call for different responses. ValueError can mean a value has the wrong form; IndexError can mean a list position does not exist. The exception’s type, not its message, determines which handler matches.
def read_position(text, names):
try:
position = int(text)
return names[position]
except ValueError:
return "Position must be an integer"
except IndexError:
return "No name at that position"
print(read_position("1", ["Mina", "Omar"]))
print(read_position("blue", ["Mina", "Omar"]))
print(read_position("5", ["Mina", "Omar"]))
Omar
Position must be an integer
No name at that position
The first handler applies to int(text); the second applies to indexing. Negative indexes are valid when they count from the end within the list. Keep the try small enough that each handler covers operations whose failure it can actually address. Returning a message here is a deliberate interface choice; another program might report a problem separately instead of mixing names and messages.
Handlers are considered in order. Exception matches many ordinary exceptions including ValueError, so a general except Exception placed first would also catch the more specific cases. Prefer specific handlers, and place a broad handler after them only when the program has a meaningful way to respond. Exception("division by zero") remains an Exception; its words do not make it a ZeroDivisionError. Catching everything indiscriminately can conceal a programming defect.
A try statement may also have else for code that runs only when the try succeeds, and finally for cleanup whether or not an exception occurred. Exceptions not handled still propagate after finally.
try:
value = int("14")
except ValueError:
print("invalid")
else:
print("parsed", value)
finally:
print("finished attempt")
parsed 14
finished attempt