Example of Catching an Exception Thrown by the .NET Framework

Below is a complete example that shows how we might catch an exception thrown by the .NET Framework.
Our Dog class builds a list of all dogs created and allows you to retrieve a dog by index.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Dog
{
    private static List<Dog> _allDogs = new List<Dog>();
 
    public string Name { get; set; }
    public int Age { get; set; }
 
    // Standard constructor
    public Dog(string name, int age)
    {
        Name = name;
        Age = age;
        <span class="skimlinks-unlinked">_allDogs.Add(this</span>);
    }
 
    public static Dog DogByIndex(int index)
    {
        return _allDogs[index];
    }
}
We can protect code that calls the DogByIndex method with a try-catch statement.
1
2
3
4
5
6
7
8
9
10
11
12
13
try
{
    Dog d1 = new Dog("Kirby", 15);
    Dog d2 = new Dog("Ruby", 3);
 
    // Later, get dog by index
    Dog someDog = Dog.DogByIndex(2);  // Oops--index of 2 is wrong!
}
catch (ArgumentOutOfRangeException exc)
{
    Console.WriteLine("The dog index you used is out of range!");
    Console.WriteLine(exc.Message);
}


869-001