Python Exception Handling
Use try/except/finally blocks, raise exceptions, and write custom exception classes.
What is an Exception?
An exception is an error that occurs at runtime — Python encounters something it
can't handle and stops the program. Without exception handling, a single bad input crashes everything.
The try/except block lets you catch specific errors and respond gracefully, keeping the
program running and giving users helpful messages.
try / except
Code that might fail goes inside try. If an exception occurs, Python jumps to the
matching except block and runs it. If no exception occurs, except is skipped.
Name the exception as e to access its message.
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") try: num = int("hello") except ValueError as e: print(f"Bad conversion: {e}")
Cannot divide by zero! Bad conversion: invalid literal for int() with base 10: 'hello'
Multiple except + finally
You can have multiple except clauses for different error types. The finally
block always runs — whether or not an exception occurred. Use it for cleanup that must always happen
(closing connections, releasing resources).
def safe_div(a, b): try: print(f"Result: {a / b}") except ZeroDivisionError: print("Zero division!") except TypeError: print("Wrong types!") finally: print("--- done ---") safe_div(10, 2) safe_div(10, 0)
Result: 5.0 --- done --- Zero division! --- done ---
Raising Exceptions
Use raise to intentionally trigger an exception when invalid data is detected.
This enforces rules in your code — for example, rejecting a negative age or a too-short password.
def set_age(age): if age < 0 or age > 150: raise ValueError(f"Age {age} is out of range (0–150)") return age try: set_age(-5) except ValueError as e: print(f"Error: {e}")
Error: Age -5 is out of range (0–150)
except:. A bare except catches everything including keyboard interrupts, making your program hard to stop.🧠 Quick Check
Which block always runs regardless of exceptions?