C++/Exception 2021. 3. 22. 00:12

함수 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()
    */