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
?
:) 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.
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.
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!
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.
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.
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.
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