The set_exception_handler Function
The set_exception_handler
function allows you to define a function that will be called to handle uncaught exceptions. It takes either the name of the handler function or an anonymous function as a parameter. The handler receives the exception object as its parameter.
Syntax
set_exception_handler(callable $exception_handler): callable
Example
Let's set a simple exception handler:
<?php
function myExceptionHandler($exception) {
echo 'Caught exception: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Something went wrong!');
?>
Code execution result:
'Caught exception: Something went wrong!'
Example
Using an anonymous function as a handler:
<?php
set_exception_handler(function($exception) {
echo 'Error: ' . $exception->getMessage();
});
throw new Exception('Critical error');
?>
Code execution result:
'Error: Critical error'
Example
Restoring the previous handler:
<?php
function firstHandler($exception) {
echo 'First handler: ' . $exception->getMessage();
}
function secondHandler($exception) {
echo 'Second handler: ' . $exception->getMessage();
}
set_exception_handler('firstHandler');
$old_handler = set_exception_handler('secondHandler');
restore_exception_handler(); // Restores firstHandler
throw new Exception('Test');
?>
Code execution result:
'First handler: Test'