try / except / else / finally
Errors happen
An exception is an error raised while the program runs: ZeroDivisionError, ValueError, KeyError, FileNotFoundError, TypeError… If nothing catches it, the program stops and prints a traceback. Read it from the bottom up: the last line says what went wrong, and the lines above say where.
The full structure
try:
risky() # code that might fail
except ValueError as e:
handle(e) # runs only if that error happened
else:
success() # runs only if NO error happened
finally:
cleanup() # always runs
- Catch specific exceptions, never a bare
except:. It hides real bugs and even Ctrl+C. - Catch several at once:
except (ValueError, TypeError): - Keep the
tryblock small: only the line that can fail.
Raising your own
raise ValueError("age must be positive") stops the function with a clear message.
💡 "It's easier to ask forgiveness than permission" (EAFP): Python style often tries first and handles the error, instead of checking everything beforehand.
▶️ Runs in the app.
Example
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Can't divide by zero")
return None
else:
print("Division OK")
return result
finally:
print("Done")
print(safe_divide(10, 2)) # Division OK / Done / 5.0
print(safe_divide(1, 0)) # Can't divide by zero / Done / None
def parse_age(text):
age = int(text) # may raise ValueError
if age < 0:
raise ValueError("age must be positive")
return age
for value in ["21", "abc", "-5"]:
try:
print(parse_age(value))
except ValueError as e:
print(f"Invalid '{value}': {e}")