
PHP에서 throws 키워드를 사용하여 exception을 만들 때, Throwable::__toString() 메소드를 override하여 custom exception message를 출력할 수 있습니다.
Throwable::__toString() 메소드를 override하면, exception이 발생했을 때 기본적으로 제공되는 default message가 아닌 custom message가 출력됩니다.
custom message를 출력하기 위해서는 다음 절차를 밟아야 합니다.
1. Exception 클래스를 상속하여 custom exception 클래스를 생성합니다.
2. custom exception 클래스에서 Throwable::__toString() 메소드를 override합니다.
3. override한 메소드에 custom exception message를 반환합니다.
예를 들어, custom exception 클래스를 생성하고 Throwable::__toString() 메소드를 override한 예제는 다음과 같습니다.
#hostingforum.kr
php
class CustomException extends Exception {
public function __toString() {
return '커스텀 예외 메시지';
}
}
try {
throw new CustomException();
} catch (CustomException $e) {
echo $e;
}
위의 예제에서 CustomException 클래스는 Exception 클래스를 상속하고 Throwable::__toString() 메소드를 override하여 custom exception message를 반환합니다. 따라서 exception이 발생했을 때 custom message가 출력됩니다.
2025-03-16 06:13