Exceptions - Multiple Catch Clauses


The examples to date have had a single catch clause. It is possible (and common) for a program to form multiple handlers in a try-catch statement. The next program is a variation on the previous program where there are two possible errors, and each error is caught with a different exception type.

// Exception6 - Multiple Catch Clauses

using System;

class Program
{
    static void Main()
    {
        int[] numerators = { 4, 10, 100, 3, 5, 8 , 13, 15};
        int[] denominators = { 2, 5, 0, 3, 0, 4 };

        for (int i = 0; i < numerators.Length; i++)
            try
            {
                Console.WriteLine("{0} / {1} = {2}", numerators[i],
                                                     denominators[i],
                                                     numerators[i] / denominators[i]);
            }
            catch (DivideByZeroException)
            {
                Console.WriteLine("Attempted to divide by zero");
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("No denominator available");
            }
    }
}

Like before, the denominator being zero in an integer division causes the runtime to throw the exception DivideByZeroException. In this program, the array of denominators is shorter than the array of numerators, giving rise also to an IndexOutOfRangeException. Two catch clauses are included to accomodate the two exceptions that can arise. The output of the program is shown below.

4 / 2 = 2
10 / 5 = 2
Attempted to divide by zero
3 / 3 = 1
Attempted to divide by zero
8 / 4 = 2
No denominator available
No denominator available