An exception is a runtime error — a division by zero, a missing file, bad input. Left alone, it crashes the program. try/except lets you catch specific errors and respond gracefully, which is the difference between a robust program and a fragile one.
try / except
Put risky code in try; handle specific error types in except blocks:
try:age = int(input("Age? ")) # may raise ValueErrorresult = 100 / age # may raise ZeroDivisionErrorexcept ValueError:print("Please enter a number")except ZeroDivisionError:print("Age can't be zero")else:print(result) # runs only if NO exceptionfinally:print("done") # always runs
Catch specific exceptions
Inspecting & re-raising
try:risky()except (KeyError, IndexError) as e: # catch several typesprint(f"lookup failed: {e}")raise # re-raise after logging
Catch multiple types with a tuple, bind the error with as e to inspect it, and use a bare raise to re-throw after doing something (like logging).
Key takeaways
- 01try/except catches runtime errors so the program can continue.
- 02Catch specific exception types — never a bare except.
- 03else runs when no exception occurred; finally always runs.
- 04Catch several types with a tuple; bind with "as e" to inspect the error.
- 05Only handle errors you can meaningfully respond to; re-raise the rest.
