PHP Reference ยท Exceptions and Errors
PHP set_exception_handler() function
Reference for PHP set_exception_handler(): register a global handler for uncaught exceptions, what happens afterwards, restoring handlers and common mistakes.
set_exception_handler() registers a function that PHP calls when an exception is thrown and no catch block handles it. It is your last line of defense: a place to log the problem and show a friendly error page instead of PHP's default fatal error message.
After the handler returns, the script ends. The handler cannot resume the code that threw, so it is for reporting, not for recovery.
set_exception_handler(function (Throwable $e): void { error_log($e->getMessage()); echo "Something went wrong."; });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
set_exception_handler(?callable $callback): ?callable restore_exception_handler(): true
| Name | Description |
|---|---|
$callback |
Receives the uncaught Throwable. Pass null to remove the handler and use PHP's default behavior. |
Return value: the previously defined handler, or null if there was none. The handler's own return value is ignored.
Usage notes
- Type the parameter as
Throwable, notException. Since PHP 7 uncaughtErrorobjects (TypeError,DivisionByZeroError, ...) go to the handler too, and a handler typed withExceptionwould itself fail on them. - Execution stops afterwards. Code after the throw never runs. Registered shutdown functions and destructors still do.
- Exit code. In the CLI an uncaught exception ends with a failure status, even when your handler handled it.
- Exceptions thrown inside the handler are not passed to the handler again; PHP reports them as a fatal error.
- Not for flow control. Catch exceptions where you can do something about them. Use the global handler to log, show a generic page and set an HTTP 500 status.
- Don't leak details. Show users a short message and write the stack trace (
getTraceAsString()) to the log. - Handlers stack. Like error handlers, each new call remembers the previous one for
restore_exception_handler(). - Frameworks install their own handler; calling this function in a Laravel or Symfony app replaces it.
- Warnings and notices are not exceptions. Combine this with
set_error_handler()andErrorExceptionto cover them.