Do Not Catch Exception

ID

python.no_catch_generic_exception

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Python

Tags

CWE:396, exception-handling, reliability

Description

Reports except clauses that catch Exception or BaseException. Catching at that level also catches KeyboardInterrupt, SystemExit, MemoryError, and every programming bug (AttributeError, NameError, …​) — the program then continues running with a silently-broken assumption.

try:
    work()
except Exception:                  # FLAW
    ...
except BaseException:              # FLAW
    ...
except (Exception, OSError):       # FLAW — Exception present
    ...

try:
    work()
except (ValueError, KeyError):     # OK — specific
    ...

Rationale

The wider the catch, the bigger the risk of swallowing something the code was not designed to handle. BaseException is reserved for exit / interrupt signals; catching it means the user’s Ctrl+C is just absorbed into a regular code path. Exception is one rung better but still catches every bug class.

Remediation

Catch the exception types you actually expect:

try:
    response = requests.get(url, timeout=5)
except (requests.Timeout, requests.ConnectionError) as e:
    log.warning("network problem: %s", e)

If you genuinely need a top-level catch for a service entry point, log the exception and re-raise:

try:
    handle_request(req)
except Exception:
    log.exception("unhandled error processing request")
    raise