This rule raises an issue when a generic exception (such as ErrorException, RuntimeException or Exception) is thrown.

Why is this an issue?

Throwing generic exceptions such as Error, RuntimeException, Throwable, and Exception will have a negative impact on any code trying to catch these exceptions.

From a consumer perspective, it is generally a best practice to only catch exceptions you intend to handle. Other exceptions should ideally be let to propagate up the stack trace so that they can be dealt with appropriately. When a generic exception is thrown, it forces consumers to catch exceptions they do not intend to handle, which they then have to re-throw.

Besides, when working with a generic type of exception, the only way to distinguish between multiple exceptions is to check their message, which is error-prone and difficult to maintain. Legitimate exceptions may be unintentionally silenced and errors may be hidden.

When throwing an exception, it is therefore recommended to throw the most specific exception possible so that it can be handled intentionally by consumers.

How to fix it

To fix this issue, make sure to throw specific exceptions that are relevant to the context in which they arise. It is recommended to either:

Code examples

Noncompliant code example

function checkValue($value) {
    if ($value == 42) {
        throw new Exception("Value is 42"); // Noncompliant: This will be difficult for consumers to handle
    }
}

Compliant solution

function checkValue($value) {
    if ($value == 42) {
        throw new UnexpectedValueException("Value is 42"); // Compliant
    }
}

Resources

Standards