Errors, files and libraries · Lesson 17 of 25
Handling exceptions
try, except, else and finally without hiding errors.
8 minutes2 games
An exception interrupts normal execution. Put the operation that may fail in try and catch the expected type with except. else runs when try succeeds; finally handles cleanup whether an error occurred or not.
Python
raw = "twelve"
try:
age = int(raw)
except ValueError:
print("Enter a whole number")
else:
print(age + 1)
finally:
print("Done")Try conversion
Success → else
ValueError → except
Cleanup → finally
Spot the bug
Which line raises ValueError?
Exercise
Print Invalid if conversion fails.
Expected output: Invalid
Python
raw = "oops"
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.