Extend PHP's exception objectExtend PHP's exception object

Posted February 18th, 2010 in PHP (Updated February 25th, 2010)

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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus