Catching All Exceptions


There is syntax available for catching all exceptions that may occur. That syntax is shown in the example below.

// Exception7 - Catching All Exceptions

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
            {
                Console.WriteLine("An exception was thrown");
            }
    }
}

Two different types of exceptions occur in the above program (DivideByZeroException and IndexOutOfRangeException). Each exception is caught by the catch clause without any parameters. A catch clause without parameters catches any exception that is thrown. Such a clause can be positioned after clauses that catch a specific type. The output of the program is shown below.

4 / 2 = 2
10 / 5 = 2
An exception was thrown
3 / 3 = 1
An exception was thrown
8 / 4 = 2
An exception was thrown
An exception was thrown