MiddleDebuggingOccasionalNot answered yet
Why is this ValueError handler unreachable?
The second handler never runs, even when risky raises a ValueError.
try:
risky()
except Exception:
handle_generic()
except ValueError:
handle_value_error()
Find and fix the bug.
except Exception is checked first and catches ValueError too (it is a subclass), so the ValueError handler is unreachable (Python even flags it). Put specific exceptions before general ones. Also avoid a bare except: — it swallows KeyboardInterrupt / SystemExit.
- ✗Writing the general handler before the specific one
- ✗Thinking Python picks the most specific matching handler regardless of order
- ✗Believing
ValueErroris not a subclass ofException
- →What does Python warn about for an unreachable
exceptclause? - →Why is a bare
except:discouraged even when ordering is correct?