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
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";
}
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With