One try block with multiple excepts
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Python allows a single try block to have multiple except clauses, each handling a different exception type. This lets you respond to different error conditions with specific recovery logic rather than catching everything with a generic handler. The first matching except block executes, and the rest are skipped.
Basic Syntax
Python checks each except clause top-to-bottom and executes the first one that matches. More specific exceptions should come before general ones.
Catching Multiple Exceptions in One Block
Use a tuple to catch multiple exception types with the same handler:
This is useful when several exception types warrant the same response.
Accessing Exception Details
The as keyword binds the exception instance to a variable:
Different exception types have different attributes — FileNotFoundError has filename, JSONDecodeError has lineno and colno.
Exception Hierarchy Matters
Python exception classes form a hierarchy. A parent class catches all its subclasses:
If you put OSError first, it would catch FileNotFoundError and PermissionError too, making the specific handlers unreachable:
Using else and finally
A complete try statement can include else (runs if no exception) and finally (always runs):
Real-World Example: API Request Handling
Re-raising Exceptions
Use bare raise to re-raise the caught exception after logging or partial handling:
Common Pitfalls
- Catching Exception too early: Placing
except Exceptionbefore specific handlers makes them unreachable. Always order from most specific to most general. - Bare except:
except:(without a type) catches everything, includingSystemExitandKeyboardInterrupt. Useexcept Exception:instead to avoid swallowing system-level signals. - Silent failures: Catching an exception and doing nothing (
except: pass) hides bugs. At minimum, log the error. - Too broad a try block: Wrapping dozens of lines in one
trymakes it hard to know which line raised the exception. Keep thetryblock focused on the code that can actually fail. - Variable scope: The exception variable (
as e) is deleted after theexceptblock exits in Python 3. If you need it later, assign it to another variable first.
Summary
- A single
tryblock can have multipleexceptclauses for different exception types - Order
exceptblocks from most specific to most general - Use
(ExcA, ExcB)tuples to handle multiple exceptions the same way - Use
elsefor code that should run only when no exception occurs - Use
finallyfor cleanup that must always execute - Avoid bare
except:— preferexcept Exception:or specific types

