tags:

views:

319

answers:

3

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

+4  A: 

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.

James Hopkin
+9  A: 

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"; 
    }
};
Johannes Schaub - litb
Those constructs look good!!...
OscarRyz
+3  A: 

Herb Sutter has a good article on this: http://www.gotw.ca/gotw/066.htm.

SCFrench
thanks, i enjoyed reading it
Johannes Schaub - litb