Using Exceptions


When an exception is caught, the application can decide what action to take in order to continue processing. For example, consider the next program.

// Exception5 - Using Exceptions

using System;

class Program
{
    static void Main()
    {
        int[] numerators = { 4, 10, 100, 3, 5, 8 };
        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");
            }
    }
}

The elements of two arrays are divided. When the denominator is zero, the runtime generates an exception. The program catches the exception, prints an error message and continues running. Exceptions are an opportunity to either inform of an error or remedy the error and continue processing.

Given that the try-catch statement is executed inside a for loop, it is clear that once the exception is handled, processing continues as normal. Each pass though the for loop enters a try block and even after an exception is thrown and caught, it is quite acceptable to reenter the try block on the next pass through the loop.

The output of the above 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