O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Exception Handling

Although solving all the bugs and potential errors in your code sounds like a nice idea, it’s not likely for anything beyond “Hello, world” scripts. The main reason for this is because it’s hard to predict how your code will operate in all scenarios, so you can’t write code to handle it all.

The solution here is to write exception handlers , which allow you to explicitly state what PHP should do if there’s a problem in a block of code. Exceptions are interesting because they all come from the root class Exception, but you can extend that with your own custom exceptions to trap specific errors.

As exceptions are new in PHP 5, they are primarily for userland code (PHP code you write) as opposed to internal PHP functions. As new versions of PHP get released, more and more internal code should be switched over to use exceptions so that you have a chance to handle errors smoothly, but this is a gradual process.

The basic exception handler uses try/catch blocks to encase blocks of code in a virtual safety barrier that you can break out of by throwing exceptions. Here’s a full try/catch statement to give you an idea of how it works:

    try {
            $num = 10;
            if ($num < 20) {
                    throw new Exception("D'oh!");
            }
            $foo = "bar";
    } catch(Exception $exception) {
            print "Except!\n";
    }

In that example, PHP enters the try block and starts executing code. When it hits the line "throw new Exception", it will stop executing the try block and jump to the catch block. Here it checks each exception option ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required