PHP ExceptionsPHP Exceptions

Posted January 21st, 2010 in PHP (Updated February 25th, 2010)

PHP has an exception model that works with the newer object oriented extensions but not with the older internal functions (those use the older style error reporting instead). This is the first in a series of posts on this blog about PHP exceptions; this one gives a basic overview.

Basic example

Exception handling in PHP works like this:

try {
    // code here that may trigger an exception
}
catch(Exception $e) {
    // exception handling code here
}

How to throw an exception

If you need to trigger an exception in PHP then do this:

throw new Exception("This is an example exception", 100);

The text "This is an example exception" can be anything you want and is textual information about what the exception is about, and the option number as the second parameter is an error code number.

Various object oriented class extensions in PHP will throw their own exceptions and should be caught in try ... catch blocks.

If an exception is not handled

If an exception is not handled when it occurs, an error message similar to this will be rendered:

Fatal error: Uncaught exception 'Exception' with message 'This is an example exception' in /path/to/file.php:3
Stack trace:
#0 {main}
  thrown in /path/to/file.php on line 3

Exception Series

This is the first post in a weekly series of seven about PHP exceptions. Read the next post in this series "PHP Exceptions - available information" 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

blog comments powered by Disqus