PHP 8.0 : non-capturing catches
07, August 2021

Exceptions are great way to signal any disruptions of the normal flow of our application. It can represent a error, invalid data or logic. Any event that our softwares do not expect can be represent via exception. Alongside type improvement, PHP also improving it's exception handling system. Even, internal functions can now throw exceptions such as TypeError, ValueError. Previously they used warning for same logic.

Now, we can catch exceptions by only their type.

What does that mean? Currently, we can catch exceptions in our PHP code by try{} catch() block:

<?php

try {
    someFunction(); // function may throw RuntimeException
} catch (RuntimeException $exception) {
    // do something with $exception variable, maybe write some log
}

When someFuntion() will throw RuntimeException, our catch block will catch it and $exception variable will contain all the information of that exception. So we can do logging and other things with that variable data.


But what if we don't need any exception data? What if we only need to catch them?

PHP 8.0 allows us to catch exception only by their type, without any variable.

try {
    someFunction(); // may throw RuntimeException
} catch (RuntimeException) {
    // here, we don't have any exception data variable// but we still caught the exception
}

We can use Union Type in non-capturing catches too.

try {
    someFunction(); // may throw RuntimeException or LogicException
} catch (RuntimeException | LogicException) {
    // here, we don't have any exception data variable// but we still caught any of the RuntimeException or LogicException
}



Write comment about this article: