Lesson 29 / 47
try / except / else / finally
Catch problems gracefully instead of crashing the program.
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:.