Funktio set_exception_handler

Funktio set_exception_handler mahdollistaa funktion määrittelyn, jota kutsutaan käsittelemään kiinniotettuja poikkeuksia. Parametrina annetaan käsittelijäfunktion nimi tai anonyymi funktio. Käsittelijä saa poikkeusobjektin parametrina.

Syntaksi

phpset_exception_handler(callable $exception_handler): callable

Esimerkki

Asetetaan yksinkertainen poikkeuskäsittelijä:

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

Koodin suorituksen tulos:

php'Caught exception: Something went wrong!'

Esimerkki

Anonyymin funktion käyttö käsittelijänä:

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

Koodin suorituksen tulos:

php'Error: Critical error'

Esimerkki

Edellisen käsittelijän palauttaminen:

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(); // Palauttaa firstHandler
  
  throw new Exception('Test');
?>

Koodin suorituksen tulos:

php'First handler: Test'