Is it a good idea to throw exceptions in constructors?  
Author Message
Ben S





PostPosted: .NET Base Class Library, Is it a good idea to throw exceptions in constructors? Top

Hello,
Are there any pitfalls involved with throwing exceptions in constructors I use C# and VS2005.
Many thanks,
Ben


.NET Development31  
 
 
TaylorMichaelL





PostPosted: .NET Base Class Library, Is it a good idea to throw exceptions in constructors? Top

Throwing an exception in a constructor is a common and reasonable thing to do.  An object should always be in a consistent state when it is created.  Constructors normally permit users to initialize common properties so the constructor should do the same initialization as if the user had set the properties explicitly.

The only caveat is when you are dealing with disposable resources.  In this case you must be sure to clean them up if the constructor throws an exception.  This is because C#/.NET has an all-or-nothing philosophy so either the fully constructed instance gets returned from new or nothing does.

Here is an example of code that seems right but will actually leak a resource.

class BaseClass : IDisposable
    {
        private FileStream m_Strm;

        public BaseClass ( string fileName )
        {
            m_Strm = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        }

        public void Close ( )
        {
            Debug.WriteLine("Closing stream");
            FileStream strm = m_Strm;
            if (strm != null)
            {
                m_Strm.Close();
                m_Strm = null;
            };
        }

        void IDisposable.Dispose ( )
        {
            Close();
        }
    }

    class DerivedClass : BaseClass
    {
        public DerivedClass ( string fileName ) : base(fileName)
        {
            throw new Exception("Test failure.");
        }
    }

    class Program
    {
        static void Main ( string[] args )
        {

            {
                //Will never get here
            };
        }
    }

The problem here is that the using block will never get to wrap the object (and therefore clean it up) because the object was never created.  DerivedClass should be modified to use a try-catch around any code that may throw and call BaseClass.Close() in the catch block.  Of course if BaseClass's constructor throws an exception there is nothing you can do because C# doesn't support C++'s function exception handler syntax but then again it really doesn't need to because BaseClass should itself handle any resource clean up.

Michael Taylor - 12/7/05

 
 
Code Digger





PostPosted: .NET Base Class Library, Is it a good idea to throw exceptions in constructors? Top

I am currently experimenting with the using statement and throwing exceptions in a constructor and think the given answer is not fully correct.

- class defintion above is not the way it should be done: finalizer/destructor missing

- description not complete: if exception is thrown in constructor and object is in using list then the following appears to happen:

  • using statement terminates before entering {}
  • all objects created before exception occurred (in using list) are correctly "disposed" of
  • object that's constructor threw exception is left in a created but not disposed state and is at the mercy of the garbage collector to eventually get rid of it (and I think there could still be more to this if the constructor would take parameters and via those build references to itsself...)

So one should always implement a finalizer as described with IDisposable to ensure that cleanup will eventually take place (which most likely will happen at some point of time).