Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function try blocks, but not in constructors

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 ?

like image 845
Alexandre C. Avatar asked Oct 08 '10 10:10

Alexandre C.


People also ask

What is the difference between constructor try block and destructor try block?

:) For constructors, a function try block encompasses the construction of data members and base-classes. For destructors, a function try block encompasses the destruction of data members and base-classes.

What is the use of Try Try block in C++?

Function-try-block is a mechanism in C++ to establish an exception handler around the body of a function. The following is an example: The function foo () throws and the exception is caught in the catch block so that the function main () returns with value -1. Function-try-block can be used with regular functions, constructors, and destructors.

Can you use Try blocks with non member functions?

Although function level try blocks can be used with non-member functions as well, they typically aren’t because there’s rarely a case where this would be needed. They are almost exclusively used with constructors!

What is the use of function-try-block in Java?

The function foo () throws and the exception is caught in the catch block so that the function main () returns with value -1. Function-try-block can be used with regular functions, constructors, and destructors.


2 Answers

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.

like image 188
CB Bailey Avatar answered Oct 13 '22 02:10

CB Bailey


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.

like image 40
MSalters Avatar answered Oct 13 '22 02:10

MSalters