Error Identifier: catch.nonCapturingNotSupported
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
class HelloWorld
{
public function hello(): void
{
try {
throw new \Exception('Hello');
} catch (\Exception) {
echo 'An error occurred';
}
}
}
Why is it reported? #
Non-capturing catches were introduced in PHP 8.0. This syntax allows catching an exception without assigning it to a variable (e.g., catch (\Exception) instead of catch (\Exception $e)). When PHPStan is configured to analyse code for a PHP version earlier than 8.0, this syntax is not valid and will cause a syntax error at runtime.
How to fix it #
Assign the caught exception to a variable:
<?php declare(strict_types = 1);
class HelloWorld
{
public function hello(): void
{
try {
throw new \Exception('Hello');
- } catch (\Exception) {
+ } catch (\Exception $e) {
echo 'An error occurred';
}
}
}
Or configure PHPStan to analyse the code for PHP 8.0 or later by setting the phpVersion option in the configuration file.
Non-ignorable error #
This error cannot be ignored using @phpstan-ignore or the ignoreErrors configuration. Non-ignorable errors indicate code that would cause a crash or a fatal error at runtime, or a fundamental problem in the analysed code that must be addressed.
Rules that report this error #
- PHPStan\Rules\Exceptions\NoncapturingCatchRule [1]