Throwing Exceptions


The syntax for throwing an exception is as follows:

throw exceptionObject;

where exceptionObject is an object of a class that derives from the base exception class Exception. In the examples so far, the system has been throwing the exceptions. Below is a program that throws a system exception.

// Exception9 - Throwing Exceptions

using System;

class Program
{
    static void Main()
    {
        try
        {
            throw new IndexOutOfRangeException();
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("IndexOutOfRangeException was thrown");
        }
    }
}

A new object of the type IndexOutOfRangeException is created and thrown. The default constructor for the exception is called. Note that it is not a type that is thrown; rather, it is an object of a type (which is why the new operator is used). The type for the object is a class deriving from Exception. The exception is caught and a message is displayed.

An application may create an exception class deriving from the system class Exception and throw an object of that class. This will be done in examples that follow.