Little-known C++: function-try-block

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. Their use for functions and destructors is of little use and so far I have never seen it used in these cases. The function main() above is semantically equivalent to the following:

However, there are still gotchas that you must be aware of:

  • Exceptions from constructors and destructors of objects declared in the global namespace are not caught with function-try-catch in main().

  • Exceptions from destructors of static objects are not caught with function-try-catch in main().

  • If a function (any function, not just main()) has a return type other than void and the function-try-catch does not have a return statement in the catch block then the behaviour is undefined.

So what is then the real use of function-try-catch? The answer is catching exceptions in constructors member initializer list. Let’s take the following example:

A function-try-block is used with the constructor of bar. The exception thrown by the function foo() is caught in the catch block. If you run the program, “oops…” is printed to the console. But then, the program is aborted. The reason for this that the exception caught in the catch block of a function-try-catch of a constructor or destructor is rethrown! Therefore, the purpose of this handler is to perhaps log the error and/or run some cleanup code. Alternatively, you can throw a different exception than the one being caught, as shown in the following example:

Of course, you can have multiple catch blocks too:

It is important to note that base class destructors are called after derived class destructors but before the catch block of function-try-block of the derived destructor.

The output of this program is:

Further readings:

Note: whether C++ destructors should throw or not is another topic beyond the scope of this article.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.