When is a function try block useful?

后端 未结 6 1507
忘了有多久
忘了有多久 2020-11-30 06:31

I\'m wondering when programmers use function try blocks. When is it useful?

void f(int i)
try
{
   if ( i  < 0 ) 
      throw \"less than zero\";
   std::         


        
6条回答
  •  日久生厌
    2020-11-30 07:09

    It might be useful if you want to catch exceptions from constructor's initializer.

    However, if you do catch exception in constructor that way, you have to either rethrow it or throw new exception (i.e. you cannot just normally return from constructor). If you do not rethrow, it just happens implicitly.

    #include 
    
    class A
    {
    public:
      A()
      try {
        throw 5;
      }
      catch (int) {
        std::cout << "exception thrown\n";
        //return; <- invalid
      }
    };
    
    int main()
    {
      try {
        A a;
      }
      catch (...) {
        std::cout << "was rethrown";
      }
    }
    

提交回复
热议问题