Overly broad exception handling

Overly broad exception handling

Description

A bare except, except Exception, or an except clause catching BaseException can catch unexpected failures along with expected ones, hiding security failures and programming errors.

Potential impact

  • Authentication, validation, or file-operation failures may be handled incorrectly.
  • Operational failures or attack attempts may be obscured as ordinary errors.

Remediation

  • Catch only specific exceptions you can recover from.
  • Log and re-raise unexpected exceptions, or delegate them to a shared error-handling layer.

Examples

Before

python
try:
    return int(value)
except Exception:
    return 0

After

python
try:
    return int(value)
except ValueError:
    return 0

Explanation:

  • Before: A broad handler can hide unexpected failures as well as the intended conversion error.
  • After: The handler catches only the specific recoverable exception.

References