#869 – 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.

    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;

        public static Dog DogByIndex(int index)
            return _allDogs[index];

We can protect code that calls the DogByIndex method with a try-catch statement.

                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!");