views:

63

answers:

3

Hello, just a quick question. Is there any difference between

void f(Foo x) try
{
   ...
}
catch(exception& e)
{
   ...
}

and

void f(Foo x)
{
    try { ... }
    catch (exception& e)
    {
        ...
    }
}

?

If no, why are function try blocks for (the case of initialization lists for constructors being put aside) ? What happens if the copy constructor of Foo throws an exception when x is passed to f ?

+2  A: 

Function try blocks are only ever needed in constructors. In all other cases exactly the same effect can be achieved by enclosing the entire body of the function in a normal try/catch block.

If the copy constructor used to initialize a parameter throws an exception this happens before the function call. It cannot be caught by a function try block or exceptional handler in the function as the function doesn't get called.

Charles Bailey
Which means that function try blocks for non-constructor functions are JUST an alternative syntax, no semantic purposes, which may indeed be an arguable argument for their existence. On the other hand, there are far too many inexplicable things in C++, even among those which have nothing to do with compatibility.
Armen Tsirunyan
+1  A: 

Function try blocks were added expressly for the purpose of catching exceptions in constructor initialization lists.

In your example there are no constructor initializations, so there is no difference between the two forms.

Ferruccio
which doesn't solve the problem of static/global objects of potentially-throwing-in-constructor classes, because the exception is rethrown anyway.
Armen Tsirunyan
@Armen: Constructors _have_ to throw if the object cannot be initialized. This is the _only_ way to report construction failure.
Alexandre C.
+2  A: 

Some things are allowed because it would be harder to disallow them. Allowing function try blocks on some, but not all function bodies would make the grammar and compilers more complicated.

MSalters
Good point, that is what I thought first.
Alexandre C.