PHP: Simple Try Catch Example

With object orientated languages came the concept of the try-catch block to better manage exceptions and application crashes, and from PHP 5 onwards, the popular web server-side scripting language too adopted this ideology.

By placing code which stands a possible chance of failing within a try block, you are alerting PHP to the fact that should it fail to correctly process that chunk of code, it needs to pass control over to the code sitting within the catch block definition and then continue running after that backup code has been executed.

To see this in action, consider the code below:

try {
    $error = 'Throw this error';
    throw new Exception($error);
    echo 'Never get here';
}
catch (Exception $e)
{
    echo 'Exception caught: ' . $e->getMessage() . "\n";
}

Now admittedly in the above code block we are cheating a little by forcing the script to ‘crash’ by throwing an exception, but in the usual case we’d have pretty normal code in there like opening a file perhaps. Should it execute correctly, the application would simply continue to run, but had it failed, like we’re forcing it to do in the example above, PHP passes control over the exception handler code sitting in the catch code block, this time performing a simple echo out of the trapped error message.

So in other words, a simple but powerful tool that any current era developer should be making use of in order to better ensure the stability of their scripts.

Related Posts:

  • If your blog features a lot of code blocks or snippets, then it might be a good idea to consider displaying them in a manner that separates the code from the post text in terms of style and at the same time, go ahead and line number and colourize the code itself. One fantastic plugin that has been developed to thi ...

  • Exception handling is all well and good in PHP, try/catch blocks work pretty nice for the most part, but annoyingly enough, these don't deal, or 'catch', non exception cases like E_WARNINGs or E_NOTICEs at all.So how does one deal with them then?Well the answer is to use PHP's set_error_handler functionality, essen ...

  • Let's start this off with a quick, NEVER should you be suppressing errors instead of trying to resolve the scenarios in which an error can occur. However, if you feel that you absolutely HAVE to suppress minor error notifications that impacts on the script's overall functioning, PHP does provide a single error con ...

  • If your website can be logically split into a number of different functionalities, it makes sense to group those functionalities accordingly. In Zend terminology we are talking about modules, literally the folder splitting of logically grouped pieces of functionality. However, by default a generated Zend Framework ...

  • A PHP quick tip on something I keep on forgetting. Now while the foreach functionality is great in iterating through an array and returning the array's values, sometimes one wishes to also capture the key against which a particular value is stored and for this one should use the overloaded form of the foreach funct ...

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.

  • rayleyva

    Thanks! Glad this was the first page that popped up! BTW, you should fix your ads from adbrite on the right sidebar!

  • http://www.craiglotter.co.za Craig Lotter

    no prob rayleyva. yeah, wish big old stupid google adsense didn't boot me out. adbrite really not a great replacement at all :(

  • rayleyva

    Thanks for the heads up! Have you tried anything else? I'm looking to test out some ad networks to see if there's any difference in user response.

  • http://www.craiglotter.co.za Craig Lotter

    Using Project Wonderful over on my other site at http://www.craiglotter.co.za – so far not too bad

  • Cesar

    Very interesting, thanks! BTW, with JavaScript is the same syntax!

  • Pingback: PHP: Simple Try Catch Example | prosoxi.com