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

869-001

Advertisements

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

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: