Most C++ programmers are familiar with the concept of using a try block to catch exceptions thrown within a function. However, unless you followed the C++ Standard closely, you may not be aware of a feature that was introduced in 1995. This feature was added in reply to the question, "how do you catch an exception thrown in a constructor initializer?"
Before answering this question, let's review two relevant topics: exception handling and constructor initializers. (If you are already familiar with these topics, skip the next two sections.)
The "additional considerations" portion of this article was inspired by Herb Sutter's Guru of the Week #66 [3], which treats the those considerations in more detail.
Exceptions
C++ provides the keywords throw, try, and catch to handle situations that require bypassing the normal flow of execution (exceptions). For example:
class Error; void f() { C c; throw Error(12); } void g() { try { A a; { B b; f(); } } catch(Error &e) { cerr << e; } catch(AnotherError &ae) { ... } ... }
Here, evaluation of the throw expression throw Error(12) starts the process of stack unwinding (defined below). A throw expression consists of the keyword throw followed by an expression. The expression is usually a temporary object of a user-defined class (Error, in the example).
Stack unwinding consists of exiting blocks one by one, from the inside out, as their local objects are destroyed. In the example, the outermost block of f() is exited first, and c is destroyed. Next comes the block enclosing the call to f() and b is destroyed. Finally a is destroyed. Stack unwinding continues until the program is terminated, or until a try block with an appropriate handler is found.
A try block consists of a compound statement preceded by the keyword try and followed by one or more handlers. Each of the blocks starting with catch, plus the catch clause itself, is a handler. A handler looks similar to a function that has a single parameter and no return type. The handlers of a try block are examined in order. If no matching handler is found, stack unwinding continues.
If a handler that matches the type of the throw expression is found, execution resumes within that handler. In the example, that is the handler starting with catch(Error &e). There, e will have the value Error(12) and an appropriate output operator will be invoked to output this error (assuming such an operator has been defined).
When the end of the handler is reached, execution continues after the try block (that is, after the last handler). Handlers can themselves throw exceptions and, in particular, they can "rethrow" the exception they are handling. This is done with a throw statement (throw immediately followed by semicolon) and is used to do partial handling of an exception. If an exception is rethrown, stack unwinding continues until an outer try block with an appropriate handler is found.
Constructor Initializers
Imagine we have a class with at least one base class or member class object, something like this:
class C: public B { ... };
or something like this:
class C { M m; ... };
Every time an object of type C is constructed, an object of type B or M needs to be constructed first. This means that every constructor of C must call some constructor of class B or M. If we don't use a constructor initializer, the compiler will insert a call to the default constructor of B or M inside our C constructor.
But what if we need to call a non-default construct of B or M? We can't do this inside the body of our C constructor, since the B or M sub-objects are already constructed by the time we get there. Furthermore, constructors can't be called like regular functions:
class C: public B { M m; C(int &n) { B(n); // won't work m(n); // won't work } }
And what if the constructor needs to initialize a reference?
class C { int &r; C(int &n) { r = n; // won't work! } };
Constructor initializers were introduced specifically to handle these cases. This is how it is done:
C::C(int &n) : B(n),r(n),m(n) { ... }
The second line here is a constructor initializer. A constructor initializer is a list of comma-separated initializers (calls to constructors) starting with a colon. A constructor initializer can be used only immediately before the brace that starts the body of a constructor, hence the name.
The constructors in the list are not executed in the order they are listed, but rather in the order in which they appear in the class declaration, base classes first. Watch out for this in case you depend on construction order (generally a very bad idea).
This is the end of the review, and time to get back to our initial question.
Function Try Blocks
So, how do we catch an exception thrown in a constructor initializer? By using a function try block. Function try blocks were introduced in the April 1995 Draft C++ Standard specifically to address this problem. This is what a function try block looks like (the first line is not part of it):
C::C(int n) try : r(n),B(n),M(n) { ... } catch(Error &e) { ... } catch(AnotherError &ae) { ... }
As you can see, a function try block is similar to a regular try block, but it does not go inside the braces of a function definition. Instead, it encloses the whole function definition and the constructor initializer, if present.
Any exception thrown directly or indirectly by the execution of any of the constructors in the constructor initializer will be caught by the handler(s) of the function try block. Of course, exceptions thrown inside the braces after try will also be caught by the same handlers.
Function try blocks can be used on any function, but they are needed only for constructors that have initializers that may throw. Elsewhere, they can be replaced by a regular try block and an extra pair of braces. That is, for any function f which does not have constructor initializers:
f(...) try { ... } catch(Error &e) { ... }
can always be replaced with:
f(...) { try { ... } catch(Error &e) { ... #if <constructor/destructor> throw; #else return; #endif } }
to obtain exactly the same results.
Details
The "try" part is straightforward. Except for the fact that certain exceptions will be caught, it works pretty much like a regular function block.
The "catch" part (the handler) is more interesting. An easy way to understand it is to keep the replacement shown above in mind. As you can see, inside the handlers the parameters to the constructor are visible, but names local to the "try" part are not. For example:
C::C(int n) try : r(n),B(n),M(n) { X x; ... } catch(Error &e) { f(n); // OK f(x); // Error }
If the end of a handler is reached, the function rethrows (constructors and destructors) or returns (all other functions).
This much can be seen directly from the replacement above, but there are several further restrictions. You can't jump into the handler of a function try block or out of one, not even using return. The only way out of a handler is to reach its end or to throw an exception (and this includes rethrowing the original exception). So the handler of a constructor or destructor always exits with an exception. For example:
C::C(int n) try : r(n),B(n),M(n) { body: ... goto handler; // Error } catch(Error &e) { handler: goto body; // Error return; // Error throw; // OK throw AnotherError(10); // OK }
Any member or base class sub-objects that have been constructed are destroyed before entry into the handler. Furthermore, inside a handler you are not allowed to refer to nonstatic members or base classes. Taken together, these rules make it impossible to attempt a recovery of the failed construction. This is intentional.
C::C(int n) try : r(n),B(n),M(n) { ... } catch(Error &e) { if(...) { // silly attempts to reconstruct m m(20); // Error m = M(20); // Error } }
In case you are wondering, you cannot catch construction exceptions of namespace-scope objects, or destruction exceptions on static objects, by using a function try block on main, like this:
M m; main() try { ... } catch(Error &e) { // won't catch exceptions from construction // or destruction of m ... }
The standard explicitly says that this can't be done. After all, main is neither a constructor nor a destructor. There is no way to catch such exceptions.
Finally, keep in mind that handlers in function try blocks are processed strictly sequentially (like regular try blocks). This makes it possible to write handlers that will never be entered. In particular, if you have a handler starting with catch (...) you should put it at the end of the try block.
C::C(int n) try : r(n),B(n),M(n) { ... } catch(...) { ... } catch(Error &e) { // never reached }
Recommended Use
When should you use function try blocks? First, remember that you can't return a value inside a function-try-block handler. So it makes no sense to use a function try block for a non-void function.
int f() try { ... } catch(Error &e) { // oops, can't return int from here! }
Second, it is generally recommended that destructors not throw exceptions. There is no way to get out of a handler of a function try block of a destructor, except by throwing or re-throwing. So don't use function try blocks in destructors, unless you really know what you are doing.
C::~C() try { ... } catch(Error &e) { // will rethrow! }
Third, function try blocks are not essential in the absence of constructor initializers. Therefore, you can use function try blocks for void functions and constructors without initializers if you feel like it, but you won't accomplish anything new. As we saw above, we must use function try blocks to catch exceptions in constructor initializers. Of course, we have the option of simply letting any such exception go through, uncaught.
When should we catch, then? Notice that we can't suppress the throwing of an exception. We can either re-throw the original exception, or throw another one. This is just as well, because there is no other good way to notify the rest of the program that construction has failed.
Now let's look at things in more detail. We find ourselves in the handler of a function try block. If we got here due to a statement in the body of the constructor, but we need to recover, we are here by mistake. Instead, we should have wrapped that statement with a regular try block (possibly inside a function try block).
So, let's assume we got here due to an exception thrown directly or indirectly by a constructor invoked in the initializer list. It might seem that we could have at this point a partially constructed object. It would be difficult to determine what parts had been and what parts had not been constructed (and remember that the initializer list is not generally executed in the order given). The C++ Standard explicitly rules all of this out. Instead, it dictates that whatever has been constructed will be destroyed before we get into the handler. So whatever has been constructed has already been destroyed. Nothing remains.
Furthermore, within the handler we can't refer to non-static members or base classes, so we can't attempt to recover any part of our object. Construction fails and we must throw. All we can do is replace the exception thrown with another one (perhaps to indicate that the larger construction has failed) and possibly create some useful side effects. Perhaps the best example of a useful side effect is to log the failure or to produce some debugging output.
C::C(int n) try : r(n),B(n),M(n) { ... } catch(Error &e) { cerr << "C(int n): "; cerr << e; // let it rethrow! }
In summary, function try blocks are not intended to "recover" and attempt to reconstruct the object. All we can do is replace the exception and cause side effects.
Finally, keep in mind that initialization of built-in types never throws and that constructors with the exception-specification throw() never throw either.
If after reading all this you are still uncertain of when to use function try blocks, you can follow these guidelines:
(a) Use function try blocks only around a constructor initializer list that includes a call to at least one user-defined constructor that could throw.
(b) In such a try block, don't try to "absorb" the thrown exception; you can't.
Additional Considerations
If you want to have objects whose construction succeeds even when the construction of some of their parts fails (a dubious proposition), don't use member or base sub-objects. Use something else: pointers to additional objects, standard containers of those objects, etc. Let those pointers, containers, or whatever speak for themselves. For example, let a null pointer or an empty vector indicate that the associated objects have not been constructed. Thus, all member and base sub-objects will be fully constructed, but may be null pointers, empty containers, etc., indicating that that certain associated objects have not been constructed.
class C : public B { M *pm; ... }; C::C(int n) try : r(n),B(n) { try { pm = new M(n); } catch(...) { pm = 0; ... } } catch(Error &e) { cerr << "C(int n): "; cerr << e; // let it rethrow! }
Finally, whenever possible use "resource acquisition is initialization" (see Stroustrup, page 366). If you must acquire resources in another fashion, don't do it in the constructor initializer. It will be difficult (usually impossible) to release them properly. Do it in the body of the function using a regular try block.
C::C(int) try : B(new int[n]) // horrible! { ... } catch(Error &e) { // can't delete that int[] here! }
Current Status
The C++ Standard was approved in 1998, but like any major piece of software, it is not free of bugs. Currently, bugs are being collected by the committee and will eventually result in publication of a corrected C++ Standard. Therefore, it is good to know that there are currently no outstanding bugs reported for function try blocks. (There is a minor correction that affects both kinds of try blocks.)
I haven't done much compiler testing to say how standard-conforming most compilers are at this point. I did notice, however, non-standard behavior in gcc 2.95.2 This program compiles okay:
struct S { S(); void f(); }; S::S() try {} catch(int) {} void f() try {} catch(int) {} int main(){}
but this one doesn't:
struct S { S() try {} catch(int) {} void f() try {} catch(int) {} }; int main(){}
I get a parse error right after the function try block, but according to the C++ Standard, both programs are valid.
So it seems that gcc does not like function try blocks directly inside a class definitions, although it accepts them outside. This makes me wonder whether other compilers have similar problems and whether, in general, function try blocks are fully supported.
References
[1] ISO/IEC 14882, Programming Languages C++
[2] Bjarne Stroustrup. The C++ Programming Language, 3rd ed. (Addison-Wesley, 1997).
[3] Herb Sutter. "Guru of the Week #66," www.peerdirect.com/Resources/gotw066.html. Also watch for Herb Sutter's article, "Sutter's Mill: Constructor Failures (or The Objects That Never Were)" in the November 2000 issue of CUJ.
Alan Nash is an independent consultant with 18 years of industry experience. He is the co-author of The Elements of C Programming Style and the co-editor of The Best of Byte. He has been systems manager and systems architect at Merrill Lynch, CEO at Tesuji, and Chief Scientist at Systran Software. His interests include C++, Linux, Unicode, compilers and interpreters, natural language processing, databases, and mathematical logic. He can be reached at [email protected].