Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page