Throwing Exception
ID |
php.throwing_exception |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Php |
Tags |
error-handling, reliability |
Description
Reports throw statements that construct a base exception class — \Exception, \Error
or \ErrorException — instead of a meaningful subclass. The configurable
genericExceptions property controls which base classes are flagged.
Rationale
Throwing the root \Exception (or \Error) tells callers nothing about what went wrong
and forces them to catch the broadest possible type, which then also swallows unrelated
failures. Specific exception types let calling code react precisely — retry on a transient
fault, surface a validation message to the user, or let a programming bug propagate — and
they make stack traces self-documenting.
<?php
function process(int $qty): void
{
if ($qty < 0) {
throw new \Exception('negative quantity'); // FLAW — base class, no semantics
}
if ($qty > 1000) {
throw new \InvalidArgumentException('too large'); // OK — specific subclass
}
throw new \App\OrderException('bad order'); // OK — domain exception
}
Remediation
Replace the base class with a specific exception type. Use a built-in subclass such as
\InvalidArgumentException, \RuntimeException or \LogicException, or define a
domain-specific exception class that extends one of them. A bare rethrow (throw $e;) is
never flagged.