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; _allDogs.Add(this); } public static Dog DogByIndex(int index) { return _allDogs[index]; } }
We can protect code that calls the DogByIndex method with a try-catch statement.
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); }
Filed under: Exceptions Tagged: C#, catch, Exceptions
