Uncaught Exceptions


As previously mentioned, if an exception is thrown but not caught, the runtime catches the exception on behalf of the application, displays appropriate error messages and terminates the application. For a console program, both a windowed message is displayed and the console application also receives a message. Consider the next program.

// Exception3 - Uncaught Exceptions

using System;

class Program
{
    static void Main()
    {
        int[] ai = new int[4];

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

The bounds of the array are overrun and an exception is thrown but not caught. Firstly, the following message box is displayed.

When the dialog is dismissed, the console application then receives the following treatment.

When catching exceptions, the correct type must be specified in the catch clause; otherwise, the exception won't be caught. To illustrate this, consider the next example, which attempts to catch the wrong exception.

// Exception4 - Exception Types

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 (DivideByZeroException) // Wrong Exception Type - won't be caught
        {
            Console.WriteLine("Out of range exception caught");
        }

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

The runtime catches the exception and terminates the program. The exception passes through the above catch statement because the type of the exception in the catch clause does not match the type of the exception being thrown (which is an IndexOutOfRangeException).