Fungsi set_exception_handler

Fungsi set_exception_handler memungkinkan untuk mendefinisikan fungsi yang akan dipanggil untuk menangani pengecualian yang tidak tertangkap. Parameter yang diteruskan adalah nama fungsi penangan atau fungsi anonim. Penangan menerima objek pengecualian sebagai parameter.

Sintaks

phpset_exception_handler(callable $exception_handler): callable

Contoh

Mari kita tetapkan penangan pengecualian sederhana:

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

Hasil eksekusi kode:

php'Caught exception: Something went wrong!'

Contoh

Penggunaan fungsi anonim sebagai penangan:

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

Hasil eksekusi kode:

php'Error: Critical error'

Contoh

Memulihkan penangan sebelumnya:

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

Hasil eksekusi kode:

php'First handler: Test'