Before PHP 8, if we wanted to catch an exception, we typically needed to store it in a variable and then check that variable to retrieve the exception information. This way, developers could access detailed information about the exception, such as the error code, message, etc.
Here’s how exceptions were traditionally caught before PHP 8:
<?php
function
foo()
{
try
{
throw
new
Exception(
'Hello'
);
}
catch
(Exception
$e
) {
return
$e
->getMessage();
}
}
?>
In the code above, the exception is caught by the catch block and stored in a variable $e, which allows us to retrieve detailed information about the exception using that variable.
PHP 8 introduces the concept of non-capturing exception catches. This allows exceptions to be caught without storing them in any variable. This means that if you don't need the exception object’s details, you can simply ignore it and still handle the exception.
Here’s an example of non-capturing exception catch in PHP 8:
<?php
try
{
throw
new
Exception(
'hello'
);
}
catch
(Exception) {
// $e variable omitted
}
?>
In this example, the exception is successfully caught but not stored in any variable. This method is useful when you simply want to handle the exception without needing any information from the exception object.
The non-capturing exception catch feature in PHP 8 makes exception handling more flexible. When you don’t need to access details from the exception object, you can use this simplified approach to catch exceptions, making your code more concise, readable, and maintainable.