set_exception_handler()

set_exception_handler() — Sets a user-defined exception handler function.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

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

Signature

set_exception_handler(?callable $callback): ?callable handler(Throwable $ex): void

Parameters

ParameterTypeWhat it takes
$callback?callableThe function to be called when an uncaught exception occurs. This handler function needs to accept one parameter, which will be the Throwable object that was thrown. Both Error and Exception implement the Throwable interface. This is the handler signature:

Return value

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

Example

A runnable snippet:

function exception_handler(Throwable $exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); throw new Exception('Uncaught Exception'); echo "Not Executed\n";

Changelog

VersionChange
8.3.5The exception handler being invoked is now pushed onto the handler stack and re-installed once it returns, unless the handler modified the stack itself.
8.3.0The active exception handler is now unset while it runs, so set_exception_handler() called from within a handler reports no previously defined handler.

See also

get_exception_handler(), restore_exception_handler(), restore_error_handler(), error_reporting()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page set_exception_handler() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.