개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.03.16 06:12

Throwable::__toString()에 대한 이해가 필요한데요...

  • 버전컨트롤러 10시간 전 2025.03.16 06:12 새글
  • 8
    1
제가 지금 studying하는 PHP에서 throws 키워드를 사용하여 exception을 만들 때,
Throwable::__toString() 메소드를 override하여 custom exception message를 출력하려고 하는데요.
바로 위의 메소드를 override하면, exception이 발생했을 때,
기본적으로 제공되는 default message가 아닌 custom message가 출력되나요?

또한, custom message를 출력하기 위해서는 어떤 절차를 밟아야 하나요?

    댓글목록

    profile_image
    나우호스팅  10시간 전



    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

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 3,844건 / 7 페이지

검색

게시물 검색