[PHP OOP] 6. 예외 (Exceptions)

정현섭·2021년 6월 23일
2

PHP OOP

목록 보기
6/6

Example 1 : 기본 구조

try {
    throw new Exception('Message');
} catch(Exception $e) {
    echo $e->getMessage();
} finally {
    echo ' finally';
}
  • 위 코드의 결과로 Message finally 가 출력된다.
  • try, catch, ( + finally) 구조를 가진다.
  • finally 블록의 경우 catch가 되든 안되든 실행된다.

Example 2 : 전역 에러 처리기, 전역 예외 처리기

  • try catch문으로 catch 되지 않은 exception이나 error는 따로 처리기(handler)를 통해 처리가 가능하다.
  • set_error_handler() 로 에러를 관리할 수 있고
  • set_exception_handler() 로 예외를 관리할 수 있다.
  • 근데 fatal error의 경우 에러 핸들러에 잡히지 않는다. (주의!)

에러 핸들러, 예외 핸들러

set_error_handler(function ($errno, $errstr) {
    echo $errno . ' ' . $errstr . "\n";
});

echo $foo;
10/0;
  • 위 코드의 결과로 8 Undefined variable: foo2 Division by zero 가 출력된다.
  • 보통 아래와 같이 error handler에서 exception을 throw하고 그걸 exception hanler가 받게 해서, exception handler에서 error와 exception을 동시에 처리하는 방식을 사용한다.
set_error_handler(function ($errno, $errstr) {
    throw new ErrorException($errstr, $errno);
});

set_exception_handler(function (Exception $e) {
    echo 'caughted exception message: ' . $e->getMessage();
});

echo $foo;

위 코드의 출력은 caughted exception message: Undefined variable: foo 다.

하지만 아래 코드의 경우를 보자.

set_error_handler() : Fatal error

아래 코드는 정의 하지 않은 class Foo 를 부른다.

set_error_handler(function ($errno, $errstr) {
    echo $errno . ' ' . $errstr . "\n";
});

new Foo();
  • 위 코드의 출력 :
PHP Fatal error:  Uncaught Error: Class 'Foo' not found in /Users/hyeonseopjeong/Desktop/php/exercise/8. Exception/exception_2.3.php:7
Stack trace:
#0 {main}
  thrown in /Users/hyeonseopjeong/Desktop/php/exercise/8. Exception/exception_2.3.php on line 7
  • Fatal Error의 경우 set_error_handler() 로 핸들링하지 못하는 것을 알 수 있다.

catch Error

try {
    new Foo();
} catch(Error $e) {
    echo $e->getMessage();
}
  • 위 코드처럼 Error class로 catch를 해주면 try구문에서 일어나는 fatal error를 포함한 모든 error를 잡을 수 있다.
  • 이때 ErrorErrorException 과 다름에 유의하자!
  • ErrorException은 Exception(예외)의 한 종류다.
  • Error와 Exception은 모두 Throwable 이라는 인터페이스를 상속하고 있어서, try catch 구문에서 사용가능한 것이다.

Example 3 : 예외 클래스 만들기

  • class Exception 을 상속받아서 자신만의 예외 클래스를 만들어 사용할 수 있다.
class MyException extends Exception
{
}

try {
    throw new MyException('Message');
} catch (MyException $e) {
    echo 'This is MyException';
} catch(Exception $e) {
    echo 'This is Exception';
}
  • 위 코드는 This is MyException 을 출력한다.
  • 상위 클래스인 Exception 으로 catch할 수도 있지만 MyException 클래스에서 먼저 catch 되었기 때문이다.
  • 참고로 Throwable 인터페이스를 직접 상속받는 것 보다 Exception 클래스를 상속 받아서 예외 클래스를 만드는 것이 더 권장된다.

1개의 댓글

comment-user-thumbnail
2023년 4월 20일

6강 까지 정말 잘 보았습니다.
잘 정리하셨고 많은 도움을 받았습니다.
JAVA로 OOP 공부했는데 PHP는 다른 부분이 많은 것 같습니다.
정말 감사합니다. ^^

답글 달기