Sub topic 4
Multiple except clauses and the order they are matched
A try statement can have several except clauses, each with its own response to a different kind of failure. Which clause runs depends on their order, because Python checks them from top to bottom and stops at the first one that fits. This chapter covers that matching rule, the mistakes it causes, and how to order handlers on purpose.
This chapter assumes you can write a basic try/except, know that exceptions are classes arranged in an inheritance tree, and can read a traceback.
The matching rule
When an exception is raised inside a try block, Python walks the except clauses in the order you wrote them. For each clause it asks whether the exception is an instance of the listed class, including instances of any subclass. This is the same test as isinstance(exc, ListedClass).
- The first clause that matches runs. All later clauses are skipped, even if they would also match.
- If no clause matches, the exception keeps propagating up the call stack.
- At most one
exceptclause runs for a single exception.
Because a subclass instance counts as a match for its parent class, the hierarchy decides what a handler catches. You can inspect it directly:
import json
print([cls.__name__ for cls in json.JSONDecodeError.__mro__])This prints ['JSONDecodeError', 'ValueError', 'Exception', 'BaseException', 'object']. An except ValueError clause therefore catches a JSONDecodeError, and so does except Exception.
Put specific handlers before general ones
Order your clauses from most specific to most general. The json example from the plan shows the correct order:
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 raises JSONDecodeError, and the first clause handles it with the line and column details only that class provides. The second call raises TypeError because None is not a string. It skips the first clause and lands in the second.
Now swap the clauses:
import json
try:
json.loads('{"a": }')
except ValueError:
print("generic ValueError handler ran")
except json.JSONDecodeError:
print("never reached")This prints generic ValueError handler ran. Every JSONDecodeError is also a ValueError, so the broad clause always matches first and the specific clause can never run.
A realistic ordering: OSError and its subclasses
File and network errors are a good case for ordering. Since Python 3.3, many old exception names such as IOError and EnvironmentError are aliases of OSError. The errno-specific failures have their own subclasses.
def read_text(path):
try:
with open(path) as f:
return f.read()
except FileNotFoundError:
print(f"missing: {path}")
except PermissionError:
print(f"not allowed to read: {path}")
except OSError as exc:
print(f"other OS error: {exc.strerror}")
return None
read_text("does-not-exist.txt")FileNotFoundError and PermissionError are both subclasses of OSError, so they sit above it. The last clause is a safety net for everything else in the family, such as a disk error or IsADirectoryError. If you reversed the order, only the OSError clause would ever execute.
The two specific classes do not inherit from each other, so their relative order does not matter. Order matters only between a class and its ancestors.
Grouping types with a tuple
When several unrelated exceptions need the same response, list them in a tuple:
except (TypeError, ValueError) as exc:
...A tuple clause matches if the exception is an instance of any member. Keep these points in mind:
- The parentheses are required. Writing
except TypeError, ValueError:was aSyntaxErrorbefore Python 3.14. Python 3.14 allows it only when there is noasname. Use the parenthesized form everywhere so your code works on every version. - Older Python 2 code used
except ValueError, exc:to bind a name. That syntax no longer means that, so do not copy it from old examples. - A tuple is checked as one clause, at one position in the order. Putting a broad class inside a tuple does not exempt it from the ordering rule.
Use a tuple when the response is identical. If you would branch on the type inside the handler with isinstance, write separate clauses instead.
Handlers do not catch each other
A common misunderstanding is that a later except clause can catch an exception raised inside an earlier one. It cannot. The clauses of one try statement are alternatives for the try block only.
try:
try:
int("x")
except ValueError:
raise KeyError("from handler")
except KeyError:
print("sibling caught it")
except KeyError as exc:
print(f"outer caught: {exc}")This prints outer caught: 'from handler'. The KeyError was raised in the body of the first handler, so the sibling except KeyError is not consulted. Only an enclosing try can catch it. Python also records the original ValueError as the new exception's __context__, so a traceback would show both.
The else and finally clauses behave the same way. An exception raised in else is not handled by the except clauses of the same statement, which is why else is a good place for code that should not be covered by those handlers.
Broad handlers belong at the end, if anywhere
The last clause in a chain is where a catch-all goes, and the choice of catch-all matters.
| Clause | What it catches | Typical use |
|---|---|---|
| `except SpecificError` | That class and its subclasses | Handling a failure you know how to fix |
| `except Exception` | Almost every error raised by normal code | A boundary that logs and keeps running |
| `except BaseException` | Everything, including `KeyboardInterrupt`, `SystemExit`, and `GeneratorExit` | Rarely correct, cleanup that always re-raises |
| `except:` (bare) | Same as `BaseException` | Avoid it |
A bare except: or except BaseException: that does not re-raise will swallow Ctrl+C and sys.exit(), so the program becomes hard to stop. except Exception leaves those alone, because KeyboardInterrupt and SystemExit inherit directly from BaseException.
A catch-all also hides bugs. A typo that raises NameError or AttributeError inside the try body will be caught and reported as an ordinary failure. Put the broad clause last, log the exception with its traceback, and keep the try body as small as you can.
Checklist for ordering handlers
- List the exception classes your
trybody can raise. - Identify any that are subclasses of others in the list.
- Place each subclass before its ancestors.
- Group unrelated classes that share a response in a parenthesized tuple.
- If you need a catch-all, make it
except Exceptionand put it last. - Run a linter to confirm there are no unreachable clauses.
Exercise
The code below is meant to print a specific message for a missing key and a general message for any other lookup failure. What does it print for lookup({"a": 1}, "b"), and how do you fix it so the specific message appears?
def lookup(data, key):
try:
return data[key]
except LookupError:
print("some lookup failed")
except KeyError:
print("missing key")
lookup({"a": 1}, "b")
Show answer
It prints "some lookup failed". KeyError is a subclass of LookupError, so the first clause matches and the KeyError clause is unreachable. Swap the two clauses so that except KeyError comes first and except LookupError (which also covers IndexError) comes second. The fixed version prints "missing key".
Exercise
A handler for ValueError contains a statement that raises TypeError. The same try statement has a later except TypeError clause. Does that clause run? Explain why.
Show answer
No. The TypeError is raised inside a handler body, not inside the try block, and the except clauses of one statement only apply to exceptions from the try block. The TypeError propagates out of the statement, with the original ValueError attached as its __context__, unless an enclosing try statement catches it.