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) { ... } catch(...) { //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.
[…] issue with WordPress By msujaws Writing a blog is a new thing for me. I started blogging back in November, and since then have really liked being able to document new topics that I have learned and other […]