Wednesday, October 25, 2006

To throw or not to throw



Dispelling the myths and misgivings people have about throwing exceptions from constructors


In course of my four years of writing code, I have come across many cases where I write a C++ class that needs to do something fairly non-trivial in its constructor. The single biggest dilemma I have run into in such situations is to decide on what to do if some operation goes horribly wrong inside the constructor and all bets go off as far completing the construction is concerned.


First of all, do we throw an exception from a constructor? Is it valid C++, is it a correct practice, can it be recommended? In all this time, no one gave me an affirmative reply to any of these questions - no one from among my seniors, leads or peers. The correct answer however, to all of the questions posed here, is YES.
- Throwing exceptions from constructors is valid in C++.
- Throwing exceptions from constructors is correct and recommended when needed.


< ---- incomplete --- code examples will be added ------ >

0 Comments:

Post a Comment

<< Home