Exception Handling (try/except)
When something goes wrong — dividing by zero, converting text that isn't actually a number — Python raises an exception. Left uncaught, that crashes your program. try/except lets you catch it and decide what happens instead.
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")You cannot divide by zero!
Python tries to run the code inside try. The moment a ZeroDivisionError happens, it jumps straight to the matching except block instead of crashing — the program keeps running normally after that.
Catching the actual error, and finally
except SomeError as e lets you access the actual error object — useful for logging or showing a real message instead of a generic one. finally runs no matter what happened — whether an exception was raised or not — which makes it the right place for cleanup code.
try:
number = int("not a number")
except ValueError as e:
print(f"Error: {e}")
finally:
print("This always runs")Error: invalid literal for int() with base 10: 'not a number' This always runs
Catch specific exception types (ZeroDivisionError, ValueError) rather than a bare except — that way a genuinely unexpected bug doesn't get silently swallowed along with the error you were actually expecting.
Next: classes — bundling data and the functions that work on it together.
Practice exercise
Try converting the string "abc" to an int, catch the ValueError, and print "Not a number" instead of crashing.