One try block with multiple excepts
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
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
Related reading
- ''OneHotEncoder'' object has no attribute ''transform''
- OneToOneField vs ForeignKey in Django
- Only Add Unique Item To List
- Open file in a relative location in Python
- OnItemCLickListener not working in listview
- open in Python does not create a file if it doesn't exist
- Open files in 'rt' and 'wt' modes
- Open S3 object as a string with Boto3
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.