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

phpset_exception_handler(callable $exception_handler): callable

Example

Let's set a simple exception handler:

php<?php
  function myExceptionHandler($exception) {
    echo 'Caught exception: ' . $exception->getMessage();
  }
  
  set_exception_handler('myExceptionHandler');
  
  throw new Exception('Something went wrong!');
?>

Code execution result:

php'Caught exception: Something went wrong!'

Example

Using an anonymous function as a handler:

php<?php
  set_exception_handler(function($exception) {
    echo 'Error: ' . $exception->getMessage();
  });
  
  throw new Exception('Critical error');
?>

Code execution result:

php'Error: Critical error'

Example

Restoring the previous handler:

php<?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:

php'First handler: Test'