Is it OK to throw exceptions from constructors? Some of us may have heard that it is wrong but don’t really remember why. There are lots of philosophical arguments about this question, you may become confused trying to understand what’s the right thing to do. Does it mater if we are developing with C++ or any other .Net language like C#? I am writing this article to shed some light on the “throwing exceptions from constructors” topic.
Constructors can’t return values, so we pretty much have to throw an exception to indicate that the object couldn’t be constructed. Some of you may grasp that constructors are supposed to handle simple tasks like initialization and if someone is up to the stage where he needs to throw exceptions from constructor, reviewing his code would be a better idea. I don’t agree with that! When we get parameters to a constructor, we may need to check their validity. How would you notify about an invalid parameter? As I already said, constructors can’t return values, and I really don’t think that adding an Init() method is a good idea - it is an error prone model that permits partially constructed objects to exist.
I know that exceptions were initially invented and designed specifically to support failures in constructor. You can read Bjarne Stroustrups (who designed and implemented the C++ programming language) presentation about “Standard-Library Exception Safety” and read page 36 to see it in your own eyes. It’s reasonable for a constructor to throw an exception as long as it cleans itself up properly. If you follow the RAII paradigm (Resource Acquisition Is Initialization) then it is quite common for a constructor to do meaningful work. So, it is OK to throw exceptions from constructors in C++. Just don’t throw them from destructors…
In .Net and C# specifically, there is no single reason to avoid this behavior - the finalizer will be called even on exceptional construction. Besides that, exceptions are thrown from constructors everywhere in the .Net Framework, just look at Guid, DateTime, Queue, FileStream and many other .Net constructors. So, it is OK to throw exceptions from constructors in C# too.
Do you throw exceptions from constructors?
We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution
Learn More
Jonathan Allen Said on Dec 3, 2008 :
> Is it OK to throw exceptions from constructors?
Well the Framework Design Guidelines does say “Do throw exceptions from instance constructors, if appropriate.”
Jeremy Gray Said on Dec 4, 2008 :
Regularly. As but one small example, my constructors almost always make assertions about the state of their inbound argument values. The alternative to validating these arguments in the constructor would be to have factories for absolutely everything and, while factories are useful in many scenarios, in this case it would just be hiding the pea.
orcmid Said on Dec 5, 2008 :
Well … I actually don’t throw exceptions anywhere if I can help it, but that has to do mainly with not wanting to deal with exceptions across interop boundaries (i.e., for COM it is a no-no) and potential thread coordination issues.
Recently, for the situation that Jeremy describes, I allowed construction to succeed but a null instance is delivered that says it failed. (This was easy to do because I was using a factory and returning an interface, not a known implementation class, and null interface behavior was defined as part of the model.)
But I think you put your finger on the key issue - a constructor exception must ensure that there is clean-up as if no instance record and state was ever established, however incompletely. The only exception that I can imagine to that are system failures and the running process is not resuscitatable.
That does mean, to me, that one might be lazy about acquiring resources until after the constructor succeeds but in a way that the user of the instance doesn’t have to know or care. I do that a lot, especially to keep initialization of long-held instances from clogging up the startup of an application.
With regard to mitigating failures in constructors, one thing to avoid is leaving any instance-external resource in an unpredictable state, so no input-output or equivalent operations in the constructor, either.
[So did you put this interesting question up on StackOverflow? My RSS reader is busted so I am behind in browsing there.]
Declan Whelan Said on Dec 5, 2008 :
Absolutely, clean code should fail fast. If there is a condition that can be checked in a constructor that would prevent the class for fulfilling its responsibility then is should throw right away. Deferring the error detection obfuscates the problem for the caller and adds unnecessary conditional code within the class.
Mike Johnson Said on Dec 6, 2008 :
I agree with everything you say here, if you can’t make an instance you really have no other choice but to throw an exception. I would just add that this is best done in the very top of a constructor before any heap memory is allocated.
This makes cleanup a snap.
dennis sellinger Said on Dec 7, 2008 :
I find that throwing in a constructor is especially important when you have readonly fields (or the object is simply immutable). In this case, it is an error to return an object that is incorrect.
Ben Said on Dec 28, 2008 :
Depends on the system you are writing code for.
Most real time code do not use exceptions, in which case the 3-phase construction method is very recommended (Meaning, in general, that an object has 3 phazes of existence - Uninitialized, Initialized and “Set to work”)
Bimal pradhan Said on Sep 29, 2009 :
constructor throwing an exception:
in the catch block, when a constructor is throwing an exception, we have to set some status bit/flag to true so that
in retrun from that catch block or the inteneded person who called for creation of this object would be acessing this
and would definetely know, that ohhh ok , flag is set to true , that refers that , during my object creation it hit some excpetion
and reached the catch so the object creation failed.