Which practice is recommended when dealing with 'bare' except clauses in Python?
Trap 1: Use bare 'except:' for performance optimization.
A bare except catches BaseException, including SystemExit and KeyboardInterrupt, so it does not optimise anything; CPython's exception handling cost is unchanged by the clause's breadth. It is tempting because bare clauses look terse, but the recommended practise is naming Exception explicitly to avoid masking interpreter-level exits.
Trap 2: Use 'except Exception:' as the standard catch-all.
It is safer than bare, but still broad; catching specific exceptions is better.
Trap 3: Use 'except:' but log the error immediately.
Logging inside a bare except still catches SystemExit and KeyboardInterrupt, so shutdown and interrupt signals are swallowed before the log line runs. Logging is tempting because it adds visibility, but the recommended practise is to catch Exception explicitly, which excludes those BaseException subclasses.
- A
Use bare 'except:' for performance optimization.
Why it fails: A bare except catches BaseException, including SystemExit and KeyboardInterrupt, so it does not optimise anything; CPython's exception handling cost is unchanged by the clause's breadth. It is tempting because bare clauses look terse, but the recommended practise is naming Exception explicitly to avoid masking interpreter-level exits.
- B
Always specify the exception type you intend to catch.
A bare except catches every exception, including SystemExit and KeyboardInterrupt, masking genuine bugs. Naming the specific exception type you intend to catch satisfies the requirement to handle only anticipated failures, letting unexpected errors propagate and preserving debuggability.
- C
Use 'except Exception:' as the standard catch-all.
Why it fails: It is safer than bare, but still broad; catching specific exceptions is better.
- D
Use 'except:' but log the error immediately.
Why it fails: Logging inside a bare except still catches SystemExit and KeyboardInterrupt, so shutdown and interrupt signals are swallowed before the log line runs. Logging is tempting because it adds visibility, but the recommended practise is to catch Exception explicitly, which excludes those BaseException subclasses.