When is a function try block useful?

后端 未结 6 1512
忘了有多久
忘了有多久 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:06

    Function try block are useful for me in two contexts.

    a) To have a catch all clause around main() allowing to write small utilities without having to worry about local error handling:

    int main()
    try {
        // ...
        return 0;
    }
    catch (...) {
        // handle errors
        return -1;
    }
    

    which is clearly just syntactic sugar for having a try/catch inside main() itself.

    b) to handle exceptions thrown by base class constructors:

    struct B {
         B() { /*might throw*/ }
    };
    
    struct A : B {
         A() 
         try : B() { 
             // ... 
         } 
         catch (...) {
             // handle exceptions thrown from inside A() or by B() 
         } 
    };
    

提交回复
热议问题