Example 1 — A Last Safety Net
The handler prints a friendly message, and the line after the throw never runs.
<?php
set_exception_handler(function (Throwable $e): void {
echo "Unhandled: ", $e->getMessage(), PHP_EOL;
});
echo "Before", PHP_EOL;
throw new RuntimeException("Database is down");
echo "This line never runs", PHP_EOL; How It Works
- set_exception_handler() registers an anonymous function that receives any uncaught exception.
- The script prints Before and then throws a RuntimeException that nothing catches.
- PHP passes the exception to our function, which prints its message.
- The script ends afterwards, so the last echo is never reached.

