Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

set_exception_handler

Sets a function for exceptions nobody caught.

Syntax

set_exception_handler(?callable $callback): ?callable

Parameters

ParameterTypeDescription
$callback?callableA function receiving a `Throwable` object.

Return value

?callableThe previous handler, or `null`.

Examples

A common error page:

<?php
 
// index.php
 
set_exception_handler(function (Throwable $e) {
    error_log($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
 
    http_response_code(500);
    echo 'Something went wrong. Please try again later.';
});
 
throw new RuntimeException('Database is unavailable');

Notes

The program ends after the handler runs. Details go to the log, and the visitor sees a general phrase.

See also

  • set_error_handler — Sets a custom function to handle PHP warnings and notices.
  • Throwable — The common interface of everything that can be thrown and caught.
  • error_log — Writes a message to the error log.

In the tutorial

  • Errors and debugging — The kinds of PHP errors, error display settings, the log, turning warnings into exceptions and debugging techniques.

Thanks for reading!

Donate to the site — we work hard for you.