#874 – An Exception Can Be Thrown from a Constructor
June 26, 2013 1 Comment
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; try { myNewDog = new Dog("Methuselah", 43); Console.WriteLine("We just created an old dog"); } catch (Exception xx) { Console.WriteLine( string.Format("Caught in Main(): {0}", xx.Message)); bool nullDog = (myNewDog == null); Console.WriteLine( string.Format("myNewDog is null = {0}", nullDog)); }
It’s not true that the object is never instantiated. The instance exists, and will eventually be garbage collected and it’s destructor will be called.