Handling expected failures
Learn in depth →try/except handles selected exceptions; finally runs cleanup when control leaves the try statement.
try: ...
except ValueError as error: ...
else: ...
finally: ...Example
try:
number = int("bad")
except ValueError:
print("invalid number")
finally:
print("finished")Result
invalid number finished
Watch for: Catch the narrow failures you can handle. Returning from finally can hide a pending exception.
Practise this topic →