#880 – Catching Different Exception Types at Different Levels

You can include catch blocks at different points in the call stack, to catch different types of exceptions.

In the example below, Main calls CreateSomeDogs, which in turn creates Dog instances and calls the Dog.Bark method.  CreateSomeDogs catches exceptions of type ArgumentException, but allows other exceptions to bubble back up to the Main method, where they are caught.

When we pass in a bad age for Kirby, the exception is caught in CreateSomeDogs and we continue with the for loop.  But when we ask Jack to bark, an exception is thrown that we then catch in Main.  This means that we exit CreateSomeDogs before we get a chance to create the Ruby Dog object.

        static void Main(string[] args)
        {
            try
            {
                string[] names = { "Kirby", "Jack", "Ruby" };
                int[] ages = { 150, 13, 1 };

                CreateSomeDogs(names, ages);
            }
            catch (Exception xx)
            {
                Console.WriteLine(xx.Message);
            }

            Console.ReadLine();
        }

        static void CreateSomeDogs(string[] names, int[] ages)
        {
            if (names.Count() != ages.Count())
                throw new Exception("# Names doesn't match # Ages");

            for (int i = 0; i < names.Count(); i++)
            {
                try
                {
                    Dog d = new Dog(names[i], ages[i]);
                    d.Bark();
                }
                catch (ArgumentException exc)
                {
                    Console.WriteLine(string.Format("Bad age {0} for dog {1}", ages[i], names[i]));
                }
            }
        }
        // Dog constructor
        public Dog(string name, int age)
        {
            if (age > 30)
                throw new ArgumentException("Age too big");

            Name = name;
            Age = age;
        }

        // Dog.Bark
        public void Bark()
        {
            if (Name.Equals("Jack"))
                throw new Exception("Jack can't bark");

            Console.WriteLine(string.Format("{0}: Woof", Name));
        }

880-001

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

One Response to #880 – Catching Different Exception Types at Different Levels

  1. Pingback: Dew Drop – July 5, 2013 (#1,579) | Alvin Ashcraft's Morning Dew

Leave a comment