set_exception_handler

(PHP 5)

set_exception_handler --  Sets a user-defined exception handler function

说明

string set_exception_handler ( callback exception_handler )

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

The exception_handler must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

参数

exception_handler

Name of the function to be called when an uncaught exception occurs.

返回值

Returns the name of the previously defined exception handler, or FALSE on error. If no previous handler was defined, an empty string is returned.

范例

例子 1. 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";
?>


add a note add a note User Contributed Notes
mc-php-doco at oak dot homeunix dot org
08-Apr-2006 12:41
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 at westend dot com
21-Feb-2006 11:06
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.
sean at seanodonnell dot com
24-Oct-2005 07:48
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]