Lesson 30 / 49
try / except / else / finally
Handle errors gracefully with try, except, else and finally, and catch specific exception types.
By Rahul Agarwal · 15 years in web development · Updated 1 Oct 2026
The full structure
Risky code goes in try. Matching except blocks handle specific error types. else runs only if no error occurred; finally always runs.
try:
result = 10 / int(input("Divide by: "))
except ValueError:
print("That's not a number")
except ZeroDivisionError:
print("Can't divide by zero")
else:
print("Result:", result)
finally:
print("Done")Common exception types
Common built-in exceptions: ValueError, TypeError, KeyError, IndexError, FileNotFoundError, ZeroDivisionError. Catch the specific one you expect, not a bare except:.