Sub topic 4
Multiple except clauses and the order they are matched
This chapter assumes you can write a basic try/except statement and know that exception classes form a hierarchy, with Exception near the top and ValueError below it. You should also be able to read a simple traceback.
One try, several handlers
A single try statement can have many except clauses. Each clause gives a different response to a different kind of failure.
import json
def load(text):
try:
return json.loads(text)
except json.JSONDecodeError as exc:
print(f"bad JSON at line {exc.lineno}, column {exc.colno}")
except (TypeError, ValueError) as exc:
print(f"unexpected input: {exc}")
load('{"a": }')
load(None)The first call fails because the JSON text is malformed. The second fails because json.loads cannot parse None, which raises a TypeError. Each call is handled by a different clause.
How Python picks a handler
When an exception is raised inside the try block, Python checks the clauses from top to bottom. It runs the first clause whose class matches the exception, meaning the exception is an instance of that class or of one of its subclasses. Then it skips every remaining clause in that statement.
Two rules follow from this:
- Only one handler runs for each exception.
- If no clause matches, the exception is not handled here. It continues up the call stack to the caller.
Why order matters
json.JSONDecodeError is a subclass of ValueError. Because matching uses subclass relationships, a broad class placed first catches everything below it in the hierarchy.
import json
try:
json.loads('{"a": }')
except ValueError:
print("generic ValueError handler")
except json.JSONDecodeError:
print("never reached")This prints generic ValueError handler. The second clause can never run, because every JSONDecodeError is already a ValueError. Python accepts this code without complaint, so the bug is silent. Linters such as pylint and flake8 plugins can flag it.
The rule is to put the most specific classes first and the most general last.
Grouping with a tuple
Use a tuple when unrelated exception types need the same response:
except (TypeError, ValueError) as exc:
print(f"unexpected input: {exc}")The clause matches if the exception is an instance of any class in the tuple. Do not write except TypeError, ValueError: without parentheses. In Python 3.14 the unparenthesized form is allowed only when there is no as clause. In earlier versions it is a syntax error.
Choosing a clause layout
| Situation | Layout |
|---|---|
| Two types need different responses | Separate clauses, specific class first |
| Two unrelated types need the same response | One clause with a tuple |
| A type and its subclass need different responses | Subclass clause first, then the parent |
| You want a last-resort safety net | `except Exception` as the final clause |
Avoid a bare except: as the final clause. It also catches KeyboardInterrupt and SystemExit, which sit under BaseException, not Exception.
Common mistakes
- Putting
except Exceptionfirst, which hides every clause after it. - Listing a parent and child class in the same tuple. The child is redundant.
- Assuming that a failing handler falls through to the next clause. It does not.
Exercise
A function wraps int(value) in a try. The first clause is except Exception: and the second is except ValueError:. Which clause runs when value is "abc", and how do you fix the layout?
Show answer
The first clause runs, because ValueError is a subclass of Exception, and the ValueError clause is never reached. Swap them so except ValueError: comes first and except Exception: comes last.