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?

Tags :

14 Responses to “Throwing Exceptions From Constructors?”


  1. Jonathan Allen

    Said on December 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.”

  2. Jeremy Gray

    Said on December 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.

  3. orcmid

    Said on December 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.]

  4. Declan Whelan

    Said on December 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.

  5. Mike Johnson

    Said on December 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.

  6. dennis sellinger

    Said on December 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.

  7. Ben

    Said on December 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”)

  8. Bimal pradhan

    Said on September 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.

  9. Volker Hetzer

    Said on July 6, 2010 :

    One thing where this has real consequences is with disposable objects.
    If you go like
    using (MyClass O=new MyClass()) {…}
    and the constructor throws an exception, no Dispose() will be called because the assigment will noit happen.

    So I think the Constructor has to be like
    public MyClass()
    {
    try
    {

    }
    catch
    {
    Dispose();
    throw;
    }
    }
    so the cleanup gets performed in any case.

  10. Gabriele Iannetti

    Said on August 31, 2010 :

    Nice article!

    I haven’t known that exceptions were introduced earlier by Bjarne Stroustrups in C++ to make the constructor calls more safety.

    Thanks!

  11. Rick

    Said on September 24, 2010 :

    @Birnal pradhan

    Not sure what you’re referring to with a flag in your catch block etc. The “person” requesting the object will know something went wrong because the Exception will be thrown. It would be nice to document the types of Exceptions which could be thrown by your constructor so that the user of your code can catch the Exceptions if appropriate.

3 Trackback(s)

  1. Mar 14, 2009: 10 VISUAL STUDIO SHORTCUTS YOU MUST KNOW | Dev102.com
  2. Jun 4, 2010: Short Keys for Visual Studio | C# Guru
  3. Sep 15, 2011: Visual Studio 2008 Keyboard Shortcuts « Powertips

Post a Comment