C++ Function Try Blocks

14 November, 2008 § 1 Comment

Will it compile?

That is the question for this post. Suppose you have a class definition and constructor with an object initializer list like the following:

class CObject
   CFoo foo;
   CBar bar;

CObject::CObject() : foo(2), bar(3) {}

What would happen if there was an exception thrown in the constructor of foo? Could it be handled? Most people would want you to believe that if foo is going to throw an exception, then it is better to put it in the body of the constructor, surrounded by a try-catch block.

Actually, C++ offers a way to handle this situation. It doesn’t look nice, and doesn’t behave the exact same way as normal try-catch blocks, but could be useful. Here is how you do it:

CObject::CObject() try : foo(2), bar(3)
   //note: only static members and methods are available within this catch
   foo(0);  //illegal
   CObject::IncrementErrorCount(); //legal

   throw; //also illegal, since it will automatically be thrown

Since only static members and methods are available within the catch block, there isn’t a whole lot that can be accomplished in the way of saving your constructor from failing miserably. Also, the catch block will rethrow the exception after it returns.

Interesting. Weird. And yes, it does compile. See this Dr. Dobbs article about function try blocks for more information.

Tagged: , ,

§ One Response to C++ Function Try Blocks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

What’s this?

You are currently reading C++ Function Try Blocks at JAWS.


%d bloggers like this: