Chapter 13
Python Exception Handling
5 topics · 1 sections · beginner-friendly study notes · Updated
An exception is an error detected at run time that interrupts normal flow.
Python lets you catch it with try/except/else/finally, raise your own, handle several types and rely on a rich hierarchy of built-in exceptions.
Real programs meet bad input, missing files and network failures; robust code handles them gracefully.
Input validation, file and network I/O, database transactions, APIs and long-running services.
Exception Handling in Python
Exception handling is the mechanism for responding to run-time errors without crashing. The try block holds risky code; except blocks handle specific exceptions; else runs only if no exception occurred; finally always runs. An unhandled exception prints a traceback and terminates the program.
In short: Try something risky. If it breaks, run the rescue plan instead of letting the whole program fall over.
Think about it
The full try/except/else/finally flow is the first thing examiners ask. A form handler catches ValueError for a bad age and shows a friendly message instead of a crash.
Syntax errors are found before execution; exceptions occur during execution.
When an exception is raised Python looks for a matching except in the current function, then in the caller, and so on up the call stack (propagation).
The first matching except wins.
Use except Exception as e to access the object (message via str(e), type via type(e).
__name__).
Avoid bare except: because it also traps KeyboardInterrupt and SystemExit.
Keep the try block small so you know which line failed, and put code that should run only on success in else.
Prefer EAFP ("easier to ask forgiveness than permission") - try the operation and handle failure - over checking everything in advance (LBYL).
Key points
- Exception: Object representing an error event.
- Traceback: Report of the call stack where the exception happened.
- Propagation: Unhandled exception travelling up to callers.
- EAFP: Easier to ask forgiveness than permission.
Read more
Example
Codedef safe_div(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
return None
else:
print("division ok") # only when no exception
return result
finally:
print("done") # always
print(safe_div(10, 2))
# division ok / done / 5.0
print(safe_div(1, 0))
# Cannot divide by zero / done / None
try:
int("x")
except ValueError as e:
print("Bad value:", e) # invalid literal for int() with base 10: 'x'
def level3(): return 1 / 0
def level2(): return level3()
def level1():
try:
level2()
except ZeroDivisionError:
print("caught in level1") # propagated through level3 and level2
level1()How to Catch Multiple Exceptions in Python
Several exception types can be handled either by listing them in a tuple in one except clause - except (TypeError, ValueError) - or by writing separate except clauses, each with its own handling. Python tests clauses top to bottom and runs the first that matches.
In short: One safety net for several kinds of falls, or a different net for each kind.
Think about it
Clause ordering and tuple syntax appear in output-prediction questions. Parsing user JSON: a missing key (KeyError) and a wrong type (TypeError) both produce "invalid input".
Order specific exceptions before general ones: a clause for Exception placed first would swallow everything and later clauses become unreachable.
A tuple is ideal when the handling is identical.
Use as e to learn which one fired.
Exception classes form a hierarchy, so catching a parent such as LookupError also catches KeyError and IndexError, and ArithmeticError covers ZeroDivisionError and OverflowError.
contextlib.
suppress(Err) ignores specific exceptions in a with-block.
Python 3.11 introduced ExceptionGroup and the except* syntax for handling several simultaneous exceptions, mainly in asyncio.
Key points
- Tuple of exceptions: except (A, B): handles either type.
- Most specific first: Child classes must come before parent classes.
- contextlib.suppress: Context manager that ignores listed exceptions.
Read more
Example
Codedef parse(items, idx):
try:
return int(items[idx])
except (IndexError, ValueError) as e: # same handling for both
return f"bad input ({type(e).__name__})"
print(parse(["10", "x"], 0)) # 10
print(parse(["10", "x"], 1)) # bad input (ValueError)
print(parse(["10", "x"], 5)) # bad input (IndexError)
def lookup(d, key):
try:
return 100 / d[key]
except KeyError:
return "missing key"
except ZeroDivisionError:
return "zero value"
except Exception as e: # general handler LAST
return f"other: {type(e).__name__}"
print(lookup({"a": 4}, "a")) # 25.0
print(lookup({"a": 4}, "b")) # missing key
print(lookup({"a": 0}, "a")) # zero value
print(lookup({"a": "x"}, "a")) # other: TypeError
try:
{}["k"]
except LookupError:
print("LookupError catches KeyError")
from contextlib import suppress
with suppress(FileNotFoundError):
open("no_such_file.txt")
print("continued")Python Raise an Exception
The raise statement triggers an exception deliberately: raise ExceptionClass("message"). A bare raise inside an except block re-raises the active exception. raise NewError from original chains exceptions and stores the cause in __cause__. Custom exceptions are classes that inherit from Exception.
In short: You decide something is wrong and shout. Anything above you in the call stack can catch the shout.
Think about it
Custom exception classes and raise-from are frequent interview coding tasks. A banking function raises InsufficientFunds carrying the missing amount; the UI displays it.
Raise exceptions to signal contract violations (invalid argument, illegal state) instead of returning magic values such as -1.
Choose the closest built-in (ValueError for the right type but wrong value, TypeError for the wrong type) or define a custom class for domain errors, optionally storing extra data on it.
Chaining with from preserves the original traceback; from None hides it.
Re-raising with a bare raise keeps the original traceback intact, which is useful after logging.
assert is for internal sanity checks during development, whereas raise is for run-time validation that must always be active.
Key points
Example
Codeclass InsufficientFunds(Exception):
def __init__(self, needed):
super().__init__(f"need {needed} more")
self.needed = needed
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise InsufficientFunds(amount - balance)
return balance - amount
try:
withdraw(50, 80)
except InsufficientFunds as e:
print(e, e.needed) # need 30 more 30
try:
withdraw(50, -5)
except ValueError as e:
print("ValueError:", e)
def load_port(text):
try:
return int(text)
except ValueError as err:
raise RuntimeError("config port is invalid") from err
try:
load_port("abc")
except RuntimeError as e:
print(e, "| cause:", repr(e.__cause__))
def process():
try:
1 / 0
except ZeroDivisionError:
print("logging the error")
raise # re-raise same exception
try:
process()
except ZeroDivisionError:
print("handled by the caller")Finally Keyword in Python
The finally block is attached to a try statement and executes no matter how the try block ends: normal completion, exception, return, break or continue. It is meant for cleanup such as closing files, releasing locks and disconnecting databases.
In short: finally is the "always lock the door when you leave" step, even if you left in a hurry.
Think about it
Predicting output when finally combines with return is a classic tricky question. Always close a database connection even when the query fails.
Order with everything present: try -> (except if error) or (else if no error) -> finally.
When try contains return, the return value is computed first, then finally runs, then the function returns - unless finally itself returns or raises, which overrides the earlier result (avoid this).
If an exception is not handled, finally runs and then the exception continues to propagate.
try/finally without except is valid and common.
For files and locks prefer the with statement, which is a concise, safer form of try/finally.
finally does NOT run if the process is killed or os.
_exit() is called.
Key points
- finally: Block that always runs after try.
- Cleanup: Releasing resources like files, sockets, locks.
- try/finally: Valid without any except clause.
Example
Codedef f():
try:
return "try"
finally:
print("cleanup runs first")
print(f()) # cleanup runs first / try
def g():
try:
return 1
finally:
return 2 # overrides: avoid in real code
print(g()) # 2
try:
handle = open("missing_file.txt")
except FileNotFoundError:
print("file not found")
finally:
print("always executed")
for i in range(3):
try:
if i == 1:
continue
print("body", i)
finally:
print("finally", i) # runs even on continue
def h():
try:
1 / 0
finally:
print("cleanup then crash propagates")
try:
h()
except ZeroDivisionError:
print("caller caught it")Python Built-in Exceptions
Python ships with a hierarchy of exception classes rooted at BaseException. Almost all programmer-level errors derive from Exception. Common ones: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, NameError, AttributeError, FileNotFoundError, ImportError / ModuleNotFoundError, StopIteration, RecursionError, AssertionError and KeyboardInterrupt.
In short: Python already names most mistakes for you: wrong value, wrong type, missing key, bad index, and more.
Think about it
Matching an error scenario with the correct exception name is a standard objective question. int("abc") -> ValueError; [1,2][9] -> IndexError; {"a":1}["b"] -> KeyError; open("x") -> FileNotFoundError.
Hierarchy highlights: BaseException -> (SystemExit, KeyboardInterrupt, GeneratorExit, Exception).
Under Exception: ArithmeticError (ZeroDivisionError, OverflowError, FloatingPointError), LookupError (IndexError, KeyError), OSError (FileNotFoundError, PermissionError, TimeoutError), ValueError (UnicodeError), NameError (UnboundLocalError), ImportError (ModuleNotFoundError), RuntimeError (RecursionError, NotImplementedError), SyntaxError and AssertionError.
Catch Exception, not BaseException, in general application code.
Warnings (DeprecationWarning, UserWarning) are not exceptions unless escalated.
Use help(ExceptionName) or the official docs to look up the full tree.
Key points
- BaseException: Root of every exception class.
- LookupError: Parent of IndexError and KeyError.
- ArithmeticError: Parent of ZeroDivisionError and OverflowError.
- OSError: Parent of file/system errors like FileNotFoundError.
Read more
Example
Codetests = [
("division", lambda: 1 / 0),
("conversion", lambda: int("a")),
("type", lambda: "a" + 1),
("index", lambda: [1][5]),
("key", lambda: {}["k"]),
("name", lambda: undefined_name),
("attribute", lambda: (5).foo),
("file", lambda: open("missing.txt")),
("import", lambda: __import__("no_such_module")),
("iterator", lambda: next(iter([]))),
]
for label, action in tests:
try:
action()
except Exception as e:
print(f"{label:11} -> {type(e).__name__}: {e}")
print(issubclass(KeyError, LookupError)) # True
print(issubclass(ZeroDivisionError, ArithmeticError)) # True
print(issubclass(FileNotFoundError, OSError)) # True
print(issubclass(KeyboardInterrupt, Exception)) # False (BaseException only)
def recurse():
return recurse()
try:
recurse()
except RecursionError:
print("RecursionError: maximum recursion depth exceeded")Solved examples
Read an integer from a string safely: print the number, or "Invalid" if conversion fails.
Code
Formula Applied:—Approach note: Catch the narrowest exception that can occur.
What does this print? def f(): try: return "A" finally: print("B") print(f())
Printed lines
Formula Applied:—Approach note: finally always runs before control leaves the try statement.
Write a function set_age(age) that raises ValueError for ages outside 0-120.
Function
Formula Applied:—Approach note: Validate early and raise a specific exception.
What prints for: try: print(10 / 0) except ZeroDivisionError: print("oops") else: print("ok") finally: print("done")
Output lines
Formula Applied:—Approach note: else runs only when no exception; finally always runs.
Real-world applications
Using Python Exception Handling in real projects
Input validation, file and network I/O, database transactions, APIs and long-running services.
Common mistakes
❌ Myth: except: and except Exception: are identical.
Why this is wrong: Bare except also catches KeyboardInterrupt and SystemExit.
✅ Verified Truth: Use except Exception (or narrower).
⚠️ Exam Tip: Say "bare except hides Ctrl+C".
❌ Myth: finally runs only if an exception occurs.
Why this is wrong: It runs in every case.
✅ Verified Truth: Success, failure, return, break and continue all run finally.
⚠️ Exam Tip: Use it for cleanup, not for error handling.
❌ Myth: The order of except blocks does not matter.
Why this is wrong: The first matching clause wins.
✅ Verified Truth: Place specific exceptions before parents.
⚠️ Exam Tip: A parent first makes later clauses unreachable.
Revision notes
An exception is an error detected at run time that interrupts normal flow. Python lets you catch it with try/except/else/finally, raise your own, handle several types and rely on a rich hierarchy of built-in exceptions.
High-Yield Quick Revision Points
- try -> except -> else (no error) -> finally (always).
- Order except clauses specific to general; avoid bare except.
- raise Err("msg"); bare raise re-raises; raise X from Y chains.
- finally runs even after return/break/continue.
- KeyError/IndexError are LookupError; ZeroDivisionError is ArithmeticError.
Practice questions
Which block runs only when no exception occurs in try?
int("abc") raises
[1, 2, 3][10] raises
Which statement chains exceptions?
Custom exceptions should usually inherit from
Which is the correct syntax for two exceptions in one clause?