PHP Try Catch not Catching All Exceptions

This is something that I’ve run into a lot while programming. I’ll create a try catch statement when attempting to access a resource from a third party API and there are 10 different exceptions that need to be caught in order to prevent a 500 error from being thrown. In some cases I want to catch each individual exception but in others I want to catch all Exceptions with one catch method.

The following PHP code catches all Exceptions in a try catch statement.

try {
   $resource = $client->getResources([
} catch (\Throwable $e) {
   //throw $e;
   $resource = '';

catch (\Throwable $e) will catch all exceptions and allow you to handle the Exception rather than adding multiple catch statements targeted at catching specific Exceptions.

Leave a Reply

Your email address will not be published. Required fields are marked *