Overly broad exception handling

Overly broad exception handling

Description

Using except Exception to recover from every error can turn unexpected failures into ordinary results. A bare except or except BaseException can also catch exceptions that signal interruption or program exit.

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 the exceptions the operation can recover from. Let unexpected failures reach a shared error handler, or log them on the server and re-raise them.

Examples

Before

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

After

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

Both examples return 0 for a string that cannot be converted to an integer. Catching ValueError lets other errors propagate instead of also turning them into 0.

References