Wrong except Clause Order
ID |
python.wrong_except_order |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Python |
Tags |
exception-handling, reliability |
Description
Reports a try/except chain whose first except clauses already catch the exceptions that later clauses target — the later clauses are unreachable. The rule recognises a fixed set of broad-base classes (Exception, BaseException, plus the canonical OSError, LookupError, ArithmeticError families). When an earlier clause catches such a base, every later clause whose type is covered by the broader base is flagged.
try:
work()
except Exception:
...
except ValueError: # FLAW — already caught by Exception
...
try:
work()
except OSError:
...
except FileNotFoundError: # FLAW — covered by OSError
...
try:
work()
except ValueError: # OK — specific first
...
except Exception:
...
Rationale
The chain reads top-to-bottom; Python matches the first except whose type matches the raised exception. Putting the broad catch first means none of the later clauses ever runs — almost always the result of someone adding a specific handler later without revisiting the existing one.
Remediation
Reorder the clauses, putting the most specific exception types first and the broad catch last. If two clauses really should fire on the same condition, merge them into a single except with a tuple of types.