PHP Basics: Exceptions: Throw and Catch Tutorial

Hi there,

Today we are talking about PHP excetions, very handy stuff you know, and available from PHP5 and onwards (current at time of this article), the throw and catch is similar to other programming languages which also use ‘Try’ and ‘Catch’ exceptions.

The point of these exceptions, is that PHP can be ‘thrown’ something, and errors can be caught by the ‘catch’, it’s error handling. For each ‘Try’, there needs to be at least one ‘ Catch’, (we’ll show this in an example). However you can use mutiple ‘catch’ if necessary.

PHP will continue to search through to a matching ‘catch’ before excuting the code included in the ‘catch’.


<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World'; 
?>

Here is an example above of the PHP exception.

Tags: , , ,

Author:Alan Hamlyn

-- Alan Hamlyn Founder of Wuup
  • Richard

    wow.. what a great tutorial

  • http://www.iamboredsoiblog.com Theo

    Ha ha ha yes, taken right of the php pages.

    But I have to say… this part says it all.

    Great, thanks for sharing !

  • http://www.wuup.co.uk Alan Hamlyn

    Hi Theo,

    Thanks for stopping by, yeah it is from the php docs, but as you say, I’ve condensed it to the part that really matters :) though I’m going to go through and rewrite this one even better – wow this article is old now :P

    Alan

  • nicolas

    the try throw catch tutorial on w3c school confused me, but yours makes it all clear. Thank you!