No Catch Generic Exception
ID |
php.no_catch_generic_exception |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Php |
Tags |
CWE:396, exception-handling, reliability |
Description
Reports catch clauses whose type list contains a base exception class — \Exception,
\Throwable or \Error (with or without a leading namespace separator). Catching at that
level intercepts every failure, including ones the code is not prepared to handle.
Rationale
A catch (\Exception $e) block traps every exception thrown in the try, masking
programming bugs and unrelated failures behind one generic handler. The program then keeps
running with a broken assumption, and the real error is hidden. \Throwable is even broader,
also catching \Error (out-of-memory, type errors, …). Catching the narrowest type that
the block can genuinely recover from keeps error handling honest and lets unexpected failures
propagate. A multi-catch is flagged when any of its listed types is generic; the set of base
classes is configurable.
<?php
try {
$this->run();
} catch (\Exception $e) { // FLAW — catches the base \Exception
$this->log($e);
}
try {
$this->run();
} catch (\RuntimeException $e) { // OK — a specific subclass
$this->log($e);
}