#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));



About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #874 – An Exception Can Be Thrown from a Constructor

  1. David O'Rourke says:

    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.

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 )

Connecting to %s

%d bloggers like this: