#874 – An Exception Can Be Thrown from a Constructor

You can throw an exception from a constructor.  For example, in the code below, the Dog constructor throws an exception if an invalid age parameter is passed in.

        // Dog constructor
        public Dog(string name, int age)
            if ((age < 1) || (age > 29))
                throw new ArgumentException("Invalid dog age");

            Name = name;
            Age = age;

The code below catches an exception that happens during construction. Note that the Dog object was never instantiated, so the reference is still null.

            Dog myNewDog = null;

                myNewDog = new Dog("Methuselah", 43);
                Console.WriteLine("We just created an old dog");
            catch (Exception xx)
                    string.Format("Caught in Main(): {0}",
                bool nullDog = (myNewDog == null);
                    string.Format("myNewDog is null = {0}", nullDog));