Exceptions - Another Example


Exceptions can be generated deep within a call sequence and caught in an outer block of code. Updating the previous example, the next example is obtained. It nests the call to the array creation and causes the exception deeper within the call chain.

// Exception2 - Exceptions in Nested Call Chain

using System;


class ExceptionTest
{
    public static void Generate()
    {
        int[] ai = new int[4];

        for (int i = 0; i < 10; i++)
        {
            ai[i] = i;
            Console.WriteLine("ai[{0}] = {1}", i, ai[i]);
        }
    }
}

class Program
{
    static void Main()
    {
        try
        {
            ExceptionTest.Generate();
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Out of range exception caught");
        }

        Console.WriteLine("After try-catch statement");
    }
}

The output is quite similar to the previous example. The array within the method Generate() is automatically deallocated when the exception is thrown. After an exception is thrown, all code that is exited during exception processing is cleanly shut down. This yields an impression that the program is running in reverse until the exception is caught. All objects are automatically destroyed as layers of the program are terminated. In C++, the terminology used to express this concept is that the stack is unwound.