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 ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.