Catch mutiple exception types with PHP

Posted in PHP -

PHP's try..catch can be used to catch multiple exception types. If the try block could cause one of several different exceptions they can each be handled separately with their own catch section.

Example exceptions

Here's some example exceptions that have been defined for the purposes of this example:

class FooException extends Exception {
    public function __construct($message = null, $code = 0) {
        // do something
    }
}

class BarException extends Exception {
    public function __construct($message = null, $code = 0) {
        // do something
    }
}

class BazException extends Exception {
    public function __construct($message = null, $code = 0) {
        // do something
    }
}

Handling multiple exceptions

It's very simple - there can be a catch block for each exception type that can be thrown:

try {
    // some code that might trigger a Foo/Bar/Baz/Exception
}
catch(FooException $e) {
    // we caught a foo exception
}
catch(BarException $e) {
    // we caught a bar exception
}
catch(BazException $e) {
    // we caught a baz exception
}
catch(Exception $e) {
    // we caught a normal exception
    // or an exception that wasn't handled by any of the above
}

If an exception is thrown that is not handled by any of the other catch statements it will be handled by the catch(Exception $e) block. It does not necessarily have to be the last one.

Exception Series

This is the six post in a weekly series of seven about PHP exceptions. Read the previous post "Extend PHP's exception object", the last post in the series "Exiting from within a PHP exception" and use the links below to subscribe to my RSS feed, by email, or follow me on Twitter or Facebook to keep up to date with my daily postings.



Related posts:


Comments