Creating Your Own Exception Classes in C#

To create your own exception class, the .NET framework requires you to derive your class from the System.Exception class and recommends that you implement all the constructors that are implemented by the base class. Here are some important recommendations:

  • Give a meaningful name to your Exception class and end it with Exception.
  • Do not develop a new Exception class unless there is a scenario for developers needing the class.
  • Throw the most specific exception possible.
  • Give meaningful messages.
  • Do use InnerExceptions.
  • When wrong arguments are passed, throw an ArgumentException or a subclass of it (e.g., ArgumentNullException), if necessary.

Let's go ahead and create an exception called MyException. The code and test for the exception are shown in Listing 7.11. Output is shown in Figure 7.7.

Listing 7.11: Exception11.cs

using System;

public class MyException : Exception
{
    //Constructors. It is recommended that at least all the
    //constructors of
    //base class Exception are implemented
    public MyException() : base() { }
    public MyException(string message) : base(message) { }
    public MyException(string message, Exception e) : base(message, e) { }
    //If there is extra error information that needs to be captured
    //create properties for them.

    private string strExtraInfo;
    public string ExtraErrorInfo
    {
        get
        {
            return strExtraInfo;
        }

        set
        {
            strExtraInfo = value;
        }
    }

    public class TestMyException
    {
        public static void Main()
        {
            try
            {
                MyException m;
                m = new MyException("My Exception Occured");
                m.ExtraErrorInfo = "My Extra Error Information";
                throw m;
            }

            catch (MyException e)
            {
                Console.WriteLine(String.Concat(e.StackTrace, e.Message));
                Console.WriteLine(e.ExtraErrorInfo);
            }

            Console.ReadLine();
        }
    }
}

fig7.7.gif

Figure 7.7: Output of Listing 7.11

In Listing 7.11 we create the MyException class, which is derived from the System.Exception class. As the code shows, all constructors simply call the base class constructors the typical way to implement constructors. We also create a property called ExtraErrorInfo, which can be used to store any other extra error information. The reason you would create your own exception type is so the program catching this exception can take a specific action. You could also add your own properties to give any extra error information.

Conclusion

Hope this article would have helped you in understanding Creating Your Own Exception Classes in C#. See other articles on the website on .NET and C#.

For more info click here>>


Similar Articles