Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Non-capturing exception catches in PHP 8

June 10, 2020 ·

The usual way of handling the exception is by requiring the catch block to catch the exception (thrown from the try block) to a variable like so.

public function bar()
    try {
        throw new Exception('foo!');
    } catch (Exception $e) {
        return $e->getMessage();

Here, the exception is being catched in the catch block to a variable $e. This variable now holds any information regarding the exception such as exception message, code, trace, and so on. This is useful in logging exception information to log files or to external services.

But, in several situations, you don’t need information regarding the exception. For instance, if you just want to send a predefined email to the administrator without the need of knowing how the exception has been occurred.

Introducing non-capturing catches

For certain scenario, PHP 8 is introducing “non-capturing catches”. According to this RFC, it can be possible to catch exceptions without capturing them to variables like so.

try {
    throw new Exception('foo!');
} catch (Exception) {
    // send a predefined email to the administrator 
    // irrespective of the exception information

As you can see, the exception variable is completely omitted as the exception details are become irrelevant now.

Thanks for reading! 🚀

More in PHP 8

Learn the fundamentals of PHP 8 (including 8.1 and 8.2), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!