This is the third in a series of posts about exception handling in PHP and looks at how to specify a default exception handler. The default handler is called for any exceptions that occur which are not enclosed in a try..catch block.
Normally catch exceptions in a try..catch block
If an exception is handled inside a try..catch block it will not result in an error. For example no error will be output using the code below, unless you choose to echo something in the catch section.
When an exception occurs that is not in a try..catch block
However, if the exception occurs and is not inside a try..catch block:
then an error will be echoed to standard output:
Creating an exception handler
Normally you'd put something which could possibly have an exception into a try..catch block but it's possible instead to handle all exceptions with a specified exception handler using the set_exception_handler() function.
This may not necessarily be the best practise but it is possible to do and may help catch out errors in your code which you may not have realised could throw an exception.
This is done by defining an exception handling function and setting it like so:
Now when any exception occurs that is not handled by a try..catch block it will run the my_exception_handler() function. Obviously you can call your own exception handler whatever you want it to be.
Exception Series
This is the third post in a weekly series of seven about PHP exceptions. Read the previous post "PHP Exceptions - available information", the next post"Replace error reporting with exception handlers 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.
0 comments:
Post a Comment