PHP 8.0: catch
exceptions only by type
PHP 8.0 and later allows to use try/catch
blocks where the catch()
statement does not catch the exception itself to a variable.
Prior to PHP 8.0, a typical PHP try/catch
block must capture the exception in the catch
statement:
try {
// try something
}
catch (\InvalidArgumentException $ex) { // "$ex" is required
// handle the exception
}
Sometimes, the exception type (such as \InvalidArgumentException
) is enough to determine the way the exception is handled, and capturing the exception to a variable (such as $ex
in the example above), PHP 8.0 allows to drop the exception capturing.
try {
$container->get('api-keys.http2-pro');
}
- catch (NotFoundExceptionInterface $exception) {
+ catch (NotFoundExceptionInterface) {
$logger->log('API key not set');
}
A word of caution
Make sure that the exception type you catch
is granular enough to convey the meaning of the exception. For example, catching a wildcard \Exception
or \Throwable
without capturing the exception might be a bad idea if you intend to log the event.
Backwards Compatibility Impact
PHP versions prior to 8.0 will raise a fatal error with the new syntax:
Parse error: syntax error, unexpected ')', expecting '|' or variable (T_VARIABLE) in ... on line ...
It is not possible back-port this functionality to earlier PHP versions.
Related Changes
- Hierarchy of PHP exceptions
- Internal function warnings now throw
TypeError
andValueError
exceptions - Expressions can now
throw
Exceptions