PHP set_exception_handler() function

Example

Set user-defined exception handling function:

<?php
// User-defined exception handling function
 function myException($exception) {
     echo "<b>Exception:</b> ", $exception->getMessage();
 }
 // Set user-defined exception handling function
 set_exception_handler("myException");
// Throw exception
throw new Exception("Uncaught exception occurred!");
 ?> 

The output of the above code is similar to this:

Exception: Uncaught exception occurred!

Definition and Usage

The set_exception_handler() function sets a user-defined exception handling function.

The script will stop executing after the exception handler is called.

Syntax

set_exception_handler(exceptionhandler);
Parameters Description
exceptionhandler

Required. Specifies the name of the function to be called when an uncaught exception occurs.

Note:A NULL value can also be passed to reset the exception handler to the default value.

Technical Details

Return Value:

Returns a string containing the name of the previously defined exception handler, or NULL if an error occurs.

Also returns NULL if an error handler has not been defined previously.

If NULL is used for the parameter, the handler is reset to the default state and a TRUE is returned.

PHP Version: 5.0+
PHP Update Log:

PHP 7.0.0: Passed to exception_handler The parameter type from Exception is changed to Throwable.

Before PHP 5.5, if NULL is passed, the function returns TRUE. From PHP 5.5 onwards, it returns the previous handler.