Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Error Handling and Logging Functions : set_exception_handler

set_exception_handler

Sets a user-defined exception handler function (PHP 5)
string set_exception_handler ( callback exception_handler )

Example 597. set_exception_handler() example

<?php
function exception_handler($exception) {
 echo
"Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new
Exception('Uncaught Exception');
echo
"Not Executed\n";
?>

Code Examples / Notes » set_exception_handler

sean

Using the 'set_exception_handler' function within a class, the defined 'exception_handler' method must be declared as 'public' (preferrable 'public static' if you use the "array('example', 'exception_handler')" syntax).
<?php
class example {
public function __construct() {
@set_exception_handler(array('example', 'exception_handler'));
throw new Exception('DOH!!');
}
public static function exception_handler($exception) {
print "Exception Caught: ". $exception->getMessage() ."\n";
}
}
$example = new example;
echo "Not Executed\n";
?>
Declaring the 'exception_handler' function as 'private' causes a FATAL ERROR.
[derick: red. updated statement about static a bit]


bhyoram

to do it in command-line, use this :
echo '<?php function ff ($exception) { printf ("I am a handler, got %s\n",$exception->getMessage ()) ;} set_exception_handler ("ff") ; throw new Exception ("blabla") ; echo "This is bad\n" ;' | php


mc-php-doco

This seems not to work when calling the PHP binary with the '-r' flag.
For example, if I run it like this:
   php -r '
     function exception_handler($exception) {
       echo "Uncaught exception: " , $exception->getMessage(), "\n";
     }

     set_exception_handler("exception_handler");

     throw new Exception("Uncaught Exception");
     echo "Not Executed\n";
   '
Or if I place it in a file and run it like this:
   php -r 'include "./tmp.php";'
I get a stack trace instead of having the function 'exception_handler' called.  If run it like this:
   php tmp.php
It works fine.  
(Why run code from '-r'?  Sometimes it's useful to add stuff around the include like calls to microtime for benchmarks, or to include a library and then call a few functions from the library, all in an ad-hoc way without having to create new files.)
PHP versions 5.1.2 and 5.0.4.


ch

It seems that although the Exception contains a backtrace itself, the stack for the debug_backtrace() function is empty when entering an exception handler. This is very inconvinient. See bug #36477.

reg dot php dot manual

In my experience, the static keyword is crucial for error handlers which are methods of a class instead of free-standing functions.
static function exceptionHandler($exception)
works but
function exceptionHandler($exception)
doesn't and results in a "Fatal error: Exception thrown without a stack frame in Unknown on line 0" message.
"public" is optional as it is the default anyway (but it is probably clearer to write it explicitly).


glen

If you want a class instance to handle the exception, this is how you do it :
<?php
class example {
  public function __construct() {
      @set_exception_handler(array($this, 'exception_handler'));
      throw new Exception('DOH!!');
  }
  public function exception_handler($exception) {
      print "Exception Caught: ". $exception->getMessage() ."\n";
  }
}
$example = new example;
?>
See the first post (Sean's) for a static example.  As Sean points out, the exception_handler function must be declared public.


parazuce

I've been messing around with this function, and have noticed you can pass an anonymous function (created with create_function()) through as the default handler, for example:
set_exception_handler(create_function('$e', 'exit("An unknown error occurred");'));
That snippet of code can be used if you simply want to suppress all exceptions that are not handled.  This can be a great thing, because secure data could possibly be leaked otherwise (for example, the default exception handler could output a snippet of your SQL code that was involved with the exception being thrown).
You will want to use this wisely, however (if at all).


frank

Hey all, i've just started to use the exception suite instead of the normal PHP error suite. For those of you looking for an object orientated way to do this without looking down at Glen and Sean's examples (Lesson 1: ALWAYS read the logs!), here you go:
<?php
class NewException extends Exception
{
public function __construct($message, $code=NULL)
{
parent::__construct($message, $code);
}

public function __toString()
{
return "Code: " . $this->getCode() . "<br />Message: " . htmlentities($this->getMessage());
}

public function getException()
{
print $this; // This will print the return from the above method __toString()
}

public static function getStaticException($exception)
{
$exception->getException(); // $exception is an instance of this class
}
}
set_exception_handler(array("NewException", "getStaticException"));
throw new NewException("Catch me!!!", 69);
?>
Let me know if i'm missing something obvious as I left my glasses at home and I just came back from the Melbourne cup (If I won then I wouldn't be at work still!).


mastabog

A behaviour not documented or discussed enough, yet pretty common is that is that if an exception is thrown from the global exception handler then a fatal error occurs (Exception thrown without a stack frame). That is, if you define your own global exception handler by calling set_exception_handler() and you throw an exception from inside it then this fatal error occurs. It is only natural though, as the callback defined by set_exception_handler() is only called on uncaught (unhandled) exceptions so if you throw one from there then you get this fatal error as there is no exception handler left (you override the php internal one by calling set_exception_handler()), hence no stack frame for it.
Example:
<?php
function myExceptionHandler (Exception $ex)
{
   throw $ex;
}
set_exception_handler("myExceptionHandler");
throw new Exception("This should cause a fatal error and this message will be lost");
?>
Will cause a Fatal error: Exception thrown without a stack frame
If you skip/comment the set_exception_handler("...") line then the internal PHP global handler will catch the exception and output the exception message and trace (as string) to the browser, allowing you to at least see the exception message.
While it is a very good idea to always define your own global exception handler by using the set_exception_handler() function, you should pay attention and never throw an exception from it (or if you do then catch it).
Finally, every serious coder should use an IDE with debugging capabilities. Tracking down an error like this becomes a trivial matter by using simple debugging "Step into" commands (I for one recommend Zend IDE v5.2 at the moment of this writing). I have seen numerous messages on the internet with people wondering why this message pops up.
Cheers
p.s. Other causes for this error which are somehow unrelated to this is when you throw an exception from a destructor (the reasons behind that are similar though, the global handler might no longer exist due to the php engine shutting the page down).


Change Language


Follow Navioo On Twitter
debug_backtrace
debug_print_backtrace
error_get_last
error_log
error_reporting
restore_error_handler
restore_exception_handler
set_error_handler
set_exception_handler
trigger_error
user_error
eXTReMe Tracker