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.Barkmethod.  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 forloop.  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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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 (<span class="skimlinks-unlinked">names.Count</span>() != <span class="skimlinks-unlinked">ages.Count</span>())
        throw new Exception("# Names doesn't match # Ages");
 
    for (int i = 0; i < <span class="skimlinks-unlinked">names.Count</span>(); 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]));
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Dog constructor
public Dog(string name, int age)
{
    if (age > 30)
        throw new ArgumentException("Age too big");
 
    Name = name;
    Age = age;
}
 
// <span class="skimlinks-unlinked">Dog.Bark</span>
public void Bark()
{
    if (Name.Equals("Jack"))
        throw new Exception("Jack can't bark");
 
    Console.WriteLine(string.Format("{0}: Woof", Name));
}


880-001