Try and Catch Exceptions in PHP

I am not a big fan of the “Try Catch” syntax in PHP, but in some cases, it is necessary.

This is a way of capturing exceptions in a section of code and gives you complete control over what to do. The basic syntax is:

try {
    $divisionByZero = 1/0;
} catch (Exception $e) {
    echo 'Oh no! Maths does not work like that: ' .  $e->getMessage();
}

I find the code gets messy and hard to understand if you rely on this too much. But there are a few cases where this is useful and even necessary.

When you use 3rd party code and packages, which is very common in the PHP ecosystem, you may find that exceptions are thrown that you don’t want to show to the end user.

try {
    $api = new SomeThirdPartyAPI();
    $result = $api->doSomethingCool();
} catch (Exception $e) {
    Logger::log('some-api-error', $e->getMessage();
}

In the above example, we are catching Exceptions thrown by a third-party API library and logging them instead of outputting the Exception to the user.

There are a few more things you can do with Exceptions, such as custom Exceptions, that we will explore in a future post.

Similar Posts

Leave a Reply

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