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.
1
2
3
4
5
6
7
8
9
// 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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));
}


874-001