Extend PHP's exception object

Posted in PHP -

PHP's Exception object can be extended (just as any class can be that is not declared final) which means different exception types can be thrown that handle the exception differently.

Extending Exception

The following example extends Exception with a new class called MyException. When MyException is run it does some logging and sends an email. Exactly what the extended exception class does is up to you depending on the circumstances where it is required.

class MyException extends Exception {

    public function __construct($message = null, $code = 0) {
        parent::__construct($message, $code);
        $this->sendNotifications();
        $this->logError();
    }

    protected function sendNotifications() {
        // send some notifications here
    }

    protected function logError() {
        // do some logging here
    }

}

Throwing MyException

To cause an exception of the class MyException to occur simply do this in your code at the point where the exception needs to occur, substituting the message and error code for something a little more meaningfully than is shown in my example:

throw new MyException('This is a really bad error', 123);

As usual, the code throwing the exception should be contained within a try..catch block to avoid a fatal error message and stack trace being renderd. See my first post about PHP Exceptions for more details about catching these.

Exception Series

This is the fifth post in a weekly series of seven about PHP exceptions. Read the previous post "Replace error reporting with exception handlers with PHP", the next post "Catch mutiple exception types with PHP" 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