C++ Programming Guide

Enclosing Functions in try Blocks

If the constructor for a base class or member of a class T exits via an exception, there would ordinarily be no way for the T constructor to detect or handle the exception. The exception would be thrown before the body of the T constructor is entered, and thus before any try block in T could be entered.

A new feature in C++ is the ability to enclose an entire function in a try block. For ordinary functions, the effect is no different from placing the body of the function in a try block. But for a constructor, the try block traps any exceptions that escape from initializers of base classes and members of the constructor's class. When the entire function is enclosed in a try block, the block is called a function try block.

In the following example, any exception thrown from the constructor of base class B or member e is caught before the body of the T constructor is entered, and is handled by the matching catch block.

You cannot use a return statement in the handler of a function try block, because the catch block is outside the function. You can only throw an exception or terminate the program by calling exit() or terminate().


class B { ... };
class E { ... };
class T : public B {
public:
    T();
private:
    E e;
};
T::T()
try  : B(args), E(args)
{
    ... // body of constructor}
catch( X& x ) {
   ... // handle exception X}
catch( ... ) {
   ... // handle any other exception}