The Class Exception


In the processing of exceptions that have been present in the programs to date, no use has been made of the exception object itself. A catch clause allows the exception type and a parameter to be specified. The parameter receives the exception object. All exceptions support the members of the base class Exception. Those members will be examined here.

The class Exception defines a number of properties. Three of interest are Message, StackTrace and TargetSite. These three properties are read only. The property Message contains a string describing the error. StackTrace contains a string that holds the stack of calls that lead to the exception. TargetSite contains an object that specifies the method that generated the exception.

The class Exception also contains a number of methods. One method that is often used is the method ToString(), which generates a string that describes the exception. The method ToString() is called automatically when an exception is displayed through the method WriteLine().

The next program makes use of the above entities.

// Exception12 - The Exception Class

using System;

class Program
{
    static void GenerateException()
    {
        int[] ai = new int[4];
        for (int i = 0; i < 10; i++)
        {
            ai[i] = i;
            Console.WriteLine("ai[{0}] = {1}", i, ai[i]);
        }
    }

    static void Main()
    {
        try
        {
            GenerateException();
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("Exception ToString() is: {0}", e);
            Console.WriteLine("Stack Trace: {0}", e.StackTrace);
            Console.WriteLine("Message: {0}", e.Message);
            Console.WriteLine("TargetSite: {0}", e.TargetSite);
        }
        Console.WriteLine("After try-catch");
    }
}

The program output is as follows.

ai[0] = 0
ai[1] = 1
ai[2] = 2
ai[3] = 3
Exception ToString() is: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Program.GenerateException() in d:\CSharp\Projects\Exception12\Program.cs:line 12
   at Program.Main() in d:\CSharp\Projects\Exception12\Program.cs:line 21
Stack Trace:    at Program.GenerateException() in d:\CSharp\Projects\Exception12\Program.cs:line 12
   at Program.Main() in d:\CSharp\Projects\Exception12\Program.cs:line 21
Message: Index was outside the bounds of the array.
TargetSite: Void GenerateException()
After try-catch

Constructors

The class Exception defines 4 constructors. Two of the most commonly used are as follows.

Exception()
Exception(string message)

The second of these constructors sets the property Message to the specified string. Both of these constructors may be implemented when implementing an application defined exception class that derives from Exception.