Top Level Exception Handler
Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008
0
You can set a user-defined function as the default handler to handle all uncaught exceptions. This can be done by the set_exception_handler() function.
<?php
function myException($exception)
{
echo “<b>Exception:</b> ” , $exception->getMessage();
}
set_exception_handler(’myException’);
throw new Exception(’Uncaught Exception occurred’);
?>
function myException($exception)
{
echo “<b>Exception:</b> ” , $exception->getMessage();
}
set_exception_handler(’myException’);
throw new Exception(’Uncaught Exception occurred’);
?>
Output:
Exception: Uncaught Exception occurred
In the code above there was no “catch” block. Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions.
Rules for exceptions
- Error prone codes should be surrounded by a try block, to help catch potential exceptions
- Each try block or “throw” should have at least one corresponding catch block
- Multiple catch blocks can be used to catch different classes of exceptions
- Exceptions can be thrown or re-thrown in a catch block within a try block
If you throw something, you have to catch it.
