#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