Creating Exception Classes


To create an exception class, the program derives from the base class Exception. Generally, exceptions should be derived from the class Application Exception because this is the hierarchy reserved for application exceptions. The next program illustrates how to create an exception type.

// Exception14 - Custom Exceptions

using System;

class MyException : ApplicationException
{
    public MyException() : base("My Exception Message") {}
}


class Program
{
    static void Main()
    {
        try
        {
            throw new MyException();
        }
        catch (MyException e)
        {
            Console.WriteLine(e);
        }
    }
}

The exception message of the base class is initialized with a given string. This identifies the error when the exception is written to the console. The output of the above program is shown below.

MyException: My Exception Message
   at Program.Main() in d:\CSharp\Projects\Exception14\Program.cs:line 17