Custom Exceptions in C# – Best Practices

In .net, exceptions are objects of type Exception which are nothing but Run time errors  and Exception handling is the mechanism to handle these run time errors.If exceptions are not handled, by default, the program execution will  be terminated.Exception handling is done with the try-catch block.

                        

image 

Figure displays the Exception hierarchy in .NET. System.Exception is the base class of all exceptions.All predefined exceptions in .net are derived from System.SystemException.

Note: Initial idea was classes derived from System.SystemException would indicate exceptions thrown by CLR and classes derived from System.Applicationexception would indicate  exceptions thrown by the application.Unfortunately this policy was not reinforced and the rule was violated at various places.

For eg. System.Reflection.TargetInvocationException is an exception thrown by CLR but it is derived from System.ApplicationException.   System.SystemException class was also left open for programmers to derive from it and create custom exceptions which defeated the entire purpose of these classes.

class Program
    {
        static void Main(string[] args)
        {
        }

        [Serializable]
        public class CustomExc : System.Exception
        {
            public CustomExc(string errorMessage)
                : base(errorMessage)
            {

            }


            public CustomExc(string errorMessage, 
                System.Exception innerExc)
                : base(errorMessage, innerExc)
            {

            }

            protected CustomExc(SerializationInfo si, 
                StreamingContext sc)
                : base(si, sc)
            {

            }

            public CustomExc()
                : base()
            {
            }
        }

   Points to be noted while creating custom exception

     1.Inherit from System.Exception rather than Application.Exception while creating the exception class.

     2.Provide all 4 overloads for the constructor

    • public Exception()
    • public Exception(string message)
    • protected Exception(SerializationInfo info, StreamingContext context)
    • public Exception(string message, Exception innerException)

     3.Custom exceptions needs to be marked with the Serializable attribute because the base class implements  the  ISerializable interface.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: