Nested try Blocks


A try block can be nested within another try block. This often occurs when some errors are regarded as fatal and other errors are regarded as recoverable. The inner try block handles the recoverable errors and the outer try block catches the fatal errors (and usually terminates). In the previous example, two types of errors were encountered: an index-out-of-range error and a division-by-zero error. If the division by zero error is regarded as recoverable and the index out of range error is regarded as fatal, the application can be restructured using nested try blocks as follows.

// Exception8 - Nested try blocks

using System;

class Program
{
    static void Main()
    {
        try
        {
            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 - terminating");
        }
    }
}

When the denominator is zero, the inner try-catch statement catches the exception and prints an error (which is effectively a recovery). When there are no more denominators, there is no point continuing with the for loop. In this case, the index out of range exception is thrown and it passes through the inner catch clause. It transfers execution to the outer catch, which prints a message then cleanly terminates the program.