C Sharp

Deriving Your Own Exception Classes

As I've said, there might be times when you want to provide extra information or formatting to an exception before you throw it to the client code. You might also want to provide a base class for that situation so that your class can publish the fact that it throws only one type of exception. That way, the client only need concern itself with catching this base class.

Yet another example of when you might want to derive your own Exception class is if you wanted to perform some action-such as logging the event or sending an email to someone at the help desk-every time an exception was thrown. In this case, you would derive your own Exception class and put the needed code in the class constructor, like this: -

using System;
public class TestException : Exception
{
    // You would probably have extra methods and properties
    // here that augment the .NET Exception that you derive from.
    // Base Exception class constructors.
    public TestException()
        :base() {}
    public TestException(String message)
        :base(message) {}
    public TestException(String message, Exception innerException)
        :base(message, innerException) {}
}
public class DerivedExceptionTestApp
{
    public static void ThrowException()
    {
        throw new TestException("error condition");
    }
    public static void Main()
    {
        try
        {
            ThrowException();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

This code will generate the following output. Note that the ToString method results in a combination of properties being displayed: the textual representation of the exception class name, the message string passed to the exception's constructor, and the StackTrace.

TestException: error condition
   at DerivedExceptionTestApp.Main()