Skip to main content
Albero Academy

try / except

Handle errors gracefully instead of crashing.

Exceptions11 min

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:

catching errors
try:
age = int(input("Age? ")) # may raise ValueError
result = 100 / age # may raise ZeroDivisionError
except ValueError:
print("Please enter a number")
except ZeroDivisionError:
print("Age can't be zero")
else:
print(result) # runs only if NO exception
finally:
print("done") # always runs

Catch specific exceptions

Inspecting & re-raising

the error object
try:
risky()
except (KeyError, IndexError) as e: # catch several types
print(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

  1. 01try/except catches runtime errors so the program can continue.
  2. 02Catch specific exception types — never a bare except.
  3. 03else runs when no exception occurred; finally always runs.
  4. 04Catch several types with a tuple; bind with "as e" to inspect the error.
  5. 05Only handle errors you can meaningfully respond to; re-raise the rest.

Finished this chapter?

Mark it complete to track your progress through Python.