ErrorException 클래스

ErrorException 클래스는 기본 Exception 클래스를 상속받으며, PHP 오류를 예외로 변환하는 데 사용됩니다. 표준 예외 기능에 오류 심각도(severity) 정보를 추가합니다. 이 클래스는 특히 set_error_handler 함수와 함께 사용할 때 유용합니다.

구문

phpnew ErrorException(
  string $message = "",
  int $code = 0,
  int $severity = E_ERROR,
  string $filename = __FILE__,
  int $lineno = __LINE__,
  Throwable $previous = null
);

예제

ErrorException을 생성하고 처리하기:

php<?php
  try {
    throw new ErrorException('심각한 오류', 0, E_ERROR);
  } catch (ErrorException $e) {
    echo '오류: ' . $e->getMessage();
    echo ' 심각도: ' . $e->getSeverity();
  }
?>

코드 실행 결과:

php'오류: 심각한 오류 심각도: 1'

예제

PHP 표준 오류를 예외로 변환하기:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // 잘못된 인수 개수
  } catch (ErrorException $e) {
    echo '예외 발생: ' . $e->getMessage();
    echo ' 위치: ' . $e->getFile();
    echo ' 라인: ' . $e->getLine();
  }
?>

코드 실행 결과 (예시):

php'예외 발생: strpos()는 최소 2개의 매개변수가 필요하며, 0개가 제공되었습니다. 위치: /path/to/file.php 라인: 10'

예제

오류 심각도 정보 가져오기:

php<?php
  try {
    throw new ErrorException('경고 메시지', 0, E_WARNING);
  } catch (ErrorException $e) {
    echo '심각도 수준: ' . $e->getSeverity();
    echo ' 경고 여부: ' . ($e->getSeverity() === E_WARNING ? '예' : '아니오');
  }
?>

코드 실행 결과:

php'심각도 수준: 2 경고 여부: 예'

함께 보기

  • 클래스 Exception,
    PHP에서 모든 예외의 기본 클래스
  • 함수 set_error_handler,
    사용자 정의 오류 처리기를 설정합니다