C++ 함수 try (Function try)

2021. 3. 22. 00:12·SW개발/C++
반응형

함수 try (Function try)

함수의 body 자체가 try, catch로 이루어진 경우

  • 함수를 정의할 때 중괄호로 감싸지 않아도 된다고 한다.

  • 잘 쓰이는 문법은 아닌 것 같다.

  • rethrow를 하지 않는다.

    #include <iostream>
    
    using namespace std;
    
    void        doSomething()
    try
    {
      throw - 1;
    }
    catch (...)
    {
      cout << "Catch in doSomething()\n";
    }
    
    int            main()
    {
      try
      {
        doSomething();
      }
      catch (...)
      {
        cout << "Catch in main()\n";
      }
    }
    
    /* stdout stderr
    Catch in doSomething()
    */

클래스의 생성자에서 예외가 발생할 경우

  • 생성자의 멤버 초기화 리스트까지 포함하여 try를 시도하고, 바로 아래에서 catch한다.

  • 자동으로 rethrow를 적용한다.

    #include <iostream>
    
    using namespace std;
    
    class A
    {
      int    x_;
    
    public:
      A(int x) : x_(x)
      {
        if (x <= 0)
          throw 1;
      }
    };
    
    class B : public A
    {
    public:
      B(int x) try : A(x)
      {}
      catch (...)
      {
        cout << "Catch in B constructor\n";
        //throw;
      }
    };
    
    int            main()
    {
      try
      {
        B b(0);
      }
      catch (...)
      {
        cout << "Catch in main()\n";
      }
    }
    
    /* stdout stderr
    Catch in B constructor
    Catch in main()
    */
반응형
저작자표시 (새창열림)

'SW개발 > C++' 카테고리의 다른 글

C++ 따라하며 배우는 C++ 15장  (0) 2021.03.22
C++ 예외 처리의 위험성과 단점  (0) 2021.03.22
C++ std::exception  (0) 2021.03.22
C++ 예외 클래스와 상속 (Exception Class and Inheritance)  (0) 2021.03.22
C++ 스택 되감기 (Stack Unwinding)  (0) 2021.03.22
'SW개발/C++' 카테고리의 다른 글
  • C++ 따라하며 배우는 C++ 15장
  • C++ 예외 처리의 위험성과 단점
  • C++ std::exception
  • C++ 예외 클래스와 상속 (Exception Class and Inheritance)
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (318) N
      • SW개발 (268)
        • Java Spring (6)
        • C++ (186)
        • Python (21)
        • Linux (16)
        • 알고리즘 (13)
        • Git (4)
        • Embedded (1)
        • Raspberrypi (9)
        • React (3)
        • Web (2)
        • Windows Device Driver (6)
      • IT(개발아님) (45)
        • Windows (25)
        • MacOS (7)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2) N
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    스프링
    unix
    Workspace
    windows
    java
    윈도우
    mspaint
    vscode
    Solaris 10
    알림
    백기선
    Windows 11
    스프링 프레임워크 핵심 기술
    시스템 복구
    logi options
    맥북 카카오톡 알림 안뜸
    dism
    KakaoTalk
    로지텍 마우스 제스처
    제외
    윈도우 명령어
    EXCLUDE
    citrix workspace
    SFC
    MacOS
    SunOS 5.1
    그림판
    spring
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ 함수 try (Function try)
상단으로

티스토리툴바