#818 – What Happens When an Instance Constructor Throws an Exception

It’s possible for a normal instance constructor to throw an exception.  You can catch any exception thrown from an instance constructor and you’ll get the exact exception that was thrown.  (As opposed to exceptions thrown from static constructors, where you’ll get a TypeInitializationException).

When the exception occurs, the associated instance of the type will not be created.  The class will still function, however–you can create other instances of the type (assuming that the constructor doesn’t throw another exception) and you can access static members of the class.

        public Dog(string name, int age)
        {
            if (name == "Lassie")
                throw new Exception("No Lassies allowed");

            Name = name;
            Age = age;
        }

 

        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine(Dog.DogMotto);
                Dog d = new Dog("Lassie", 12);
            }
            catch (Exception xx)
            {
                Console.WriteLine("Error: {0}", xx.ToString());
            }

            Console.WriteLine(Dog.DogMotto);
            Dog d2 = new Dog("Bowzer", 10);
            d2.Bark();
        }

818-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #818 – What Happens When an Instance Constructor Throws an Exception

  1. Pingback: Dew Drop – April 9, 2013 (#1,523) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: