Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you really have a function/method without a body but just a try/catch block?

Tags:

c++

try-catch

g++

Note that this function does not have a "{" and "}" body. Just a try/catch block:

void func( void )
try
{
    ...
}
catch(...)
{
    ...
}

Is this intentionally part of C++, or is this a g++ extension?

Is there any purpose to this other than bypass 1 level of {}?

I'd never heard of this until I ran into http://stupefydeveloper.blogspot.com/2008/10/c-function-try-catch-block.html

like image 486
Stéphane Avatar asked Dec 02 '08 23:12

Stéphane


2 Answers

Yes, that is valid C++. One purpose i've found for it is to translate exceptions into return values, and have the code translating the exceptions in return values separate from the other code in the function. Yes, you can return x; from a catch block like the one you showed (i've only recently discovered that, actually). But i would probably just use another level of braces and put the try/catch inside the function in that case. It will be more familiar to most C++ programmers.

Another purpose is to catch exceptions thrown by an constructor initializer list, which uses a similar syntax:

struct f {
    g member;
    f() try { 
        // empty
    } catch(...) { 
        std::cerr << "thrown from constructor of g"; 
    }
};
like image 98
Johannes Schaub - litb Avatar answered Oct 20 '22 07:10

Johannes Schaub - litb


Yes, it is standard. Function try blocks, as they're called, aren't that much use for regular functions, but for constructors, they allow you to catch exceptions thrown in the initialiser list.

Note that, in the constructor case, the exception will always be rethrown at the end of any catch blocks.

like image 29
James Hopkin Avatar answered Oct 20 '22 07:10

James Hopkin