PHP Function Reference

PHP set_exception_handler() Function



The PHP set_exception_handler() function sets a user-defined exception handler function. The script will stop executing after the exception handler is called.

Syntax

set_exception_handler(callback)

Parameters

callback

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

This handler function requires one parameter which is the exception object that is thrown. Before PHP 7, The signature of this handler function was:

handler(Exception $ex): void

Since PHP 7, most errors are reported by throwing Error exceptions, which is caught by the handler as well. Both Error and Exception implements the Throwable interface. Since PHP 7, The signature of this handler function is:

handler(Throwable $ex): void

NULL can be passed to reset this handler to its default state.

Return Value

Returns the previously defined exception handler, or null on error. If no previous handler was defined, null is also returned.

Example: set_exception_handler() example

The example below shows the usage of set_exception_handler() function.

<?php
//two user-defined exception handler functions
function myException($e) {
  echo "Exception: ".$e->getMessage();
}

//sets user-defined exception handler function
set_exception_handler("myException");

//throw exception
throw new Exception("Uncaught exception occurred!");
echo "This will not be executed.\n";
?>

The output of the above code will be:

Exception: Uncaught exception occurred!

❮ PHP Error Handling Reference