Rethrowing Exceptions


Once an exception is caught, it is possible to perform some processing then rethrow the exception. Inside a handler, the following statement can be encountered.

throw;

This statement is an instruction to the compiler to rethrow the exception that was just caught. It is only valid inside an exception handler. Below is a program that catches and rethrows an exception.

// Exception10 - Rethrowing Exceptions

using System;

class Program
{
    static void GenerateException()
    {
        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 - rethrowing exception");
                throw;
            }

    }

    static void Main()
    {
        try
        {
            GenerateException();
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Fatal error encountered - terminating");
        }
    }
}

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 - rethrowing exception
Fatal error encountered - terminating

Inside the static method GenerateException() the index out of range exception is caught and rethrown. This exception is propagated back to the function Main() where it is caught again. When caught the second time, a message is printed and the application is terminated. It is apparent that this mechanism allows multiple handlers to process an exception.