Exceptions - An Example


Below is a program that causes an exception to be thrown and caught.

// Exception1 - Generating and Catching an Exception

using System;

class Program
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Inside try block");

            int[] ai = new int[4];

            for (int i = 0; i < 10; i++)
            {
                ai[i] = i;
                Console.WriteLine("ai[{0}] = {1}", i, ai[i]);
            }
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Out of range exception caught");
        }

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

An array of 4 integers is allocated. A for loop then deliberately runs off the end of the array when initializing the array. The C# runtime detects that the index is out of range and throws the exception IndexOutOfRangeException. The exception is caught and handled. After the handler is excecuted a message is written to indicate that the flow of execution is to the statement following the try-catch statement. The following printout results.

Inside try block
ai[0] = 0
ai[1] = 1
ai[2] = 2
ai[3] = 3
Out of range exception caught
After try-catch statement

The statement that caused the exception is:

ai[i] = i;

and the statement following is not executed. Rather, once the exception is thrown, control is transferred directly to the handler. The catch clause is not called, control is transferred to it. Upon entry to the handler the exception is considered handled. The handler should perform its tasks so that execution can continue after the catch clauses of the try-catch statement.

In the above program, no object was declared for the catch parameter. Often it is sufficient to know the type of the exception rather than require details of the exception. Yet other programs will require the details held by the exception object; hence, they will declare an object for the parameter.

If the try block executes without throwing an exception, no handlers are executed and control resumes after the try-catch statement. To test this, change the upper bound of the for loop in the previous program to 4 and the program will execute without any exceptions.