set_exception_handler 함수

set_exception_handler 함수는 캐치되지 않은 예외를 처리하기 위해 호출될 함수를 정의할 수 있게 해줍니다. 매개변수로는 핸들러 함수의 이름이나 익명 함수가 전달됩니다. 핸들러는 매개변수로 예외 객체를 받습니다.

문법

phpset_exception_handler(callable $exception_handler): callable

예시

간단한 예외 핸들러를 설정해 보겠습니다:

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

코드 실행 결과:

php'Caught exception: Something went wrong!'

예시

핸들러로 익명 함수 사용하기:

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

코드 실행 결과:

php'Error: Critical error'

예시

이전 핸들러 복원하기:

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(); // firstHandler를 복원합니다
  
  throw new Exception('Test');
?>

코드 실행 결과:

php'First handler: Test'