Implementing a Custom Exception class in C#

Take advantage of custom exception classes to add meaningful information to your exceptions when they are thrown in your applications

Custom Exception

Custom Exception

An exception is an error that occurs at runtime and terminates the normal flow of execution of a program if not handled properly. Exception handling is the technique of handling runtime errors in your application code. When exceptions occur, you may not want to reveal the actual stack trace or exception message to the user. Custom exceptions can be used to customize the exception information or add meaningful information to your exceptions when they occur while the program is in execution.

The base class for all exceptions in .Net is Exception. All exception classes in the exception hierarchy derive directly or indirectly from this class. Note that the System.ApplicationException and System.SystemException classes extend the System.Exception class which in turn is derived from the System.Object class. Note that exceptions are just like any other types.

ApplicationException vs System.Exception

To create a custom exception class, you should define a type. When designing custom exception classes, you should derive your class from System.Exception and not ApplicationException. Earlier, ApplicationException was used to create user defined exceptions. Although originally both of these classes were intended to differentiate the user defined exceptions and framework exceptions, the usage of ApplicationException to create a custom exception class, i.e., derive your custom exception class from ApplicationException class is no longer recommended. Note that the ApplicationException class extends the Exception class, but it doesn't add any new functionality.

The MSDN states: "An instance of the ApplicationException class is thrown by a user program, not by the CLR (common language runtime). If you are designing an application that needs to create its own exceptions, derive the exceptions from the ApplicationException class. The ApplicationException class extends the Exception class, but it does not add new functionality. This class of exceptions is provided as means of differentiating between exceptions defined by applications versus exceptions defined by the system."

The reason why ApplicationException has been deprecated is that usage of it unnecessarily increases the exception hierarchy. This is because runtime doesn't throw an instance of Application exception when a runtime error occurs -- you would rather have to throw an instance of it in your code. Also, you don't have much information on the reason why the exception occurred -- you would have to pass a custom message to the constructor of the ApplicationException class in your code.  

Designing a custom Exception class

Let's now dig into some code. In this section we'll implement a custom exception class by extending the System.Exception class. The following code snippet illustrates how you can get started creating a custom exception class in C# by deriving the System.Exception class. Note that you should provide a meaningful name to your custom exception class. In this example, we would create a custom exception class named LoginException class which can be used to trap errors that can occur at the time of logging the user in to the system, i.e., if the user credentials are incorrect.

public class LoginException : System.Exception

    {

       //TODO

    }

The following code listing shows how the custom exception class would look like with the default and argument constructors implemented.

public class LoginException : System.Exception

    {

        /// <summary>

        /// Default constructor

        /// </summary>

        public LoginException() : base()

        {

        }

        /// <summary>

        /// Argument constructor

        /// </summary>

        /// <param name="message">This is the description of the exception</param>

        public LoginException(String message) : base(message)

        {

        }

        /// <summary>

        /// Argument constructor with inner exception

        /// </summary>

        /// <param name="message">This is the description of the exception</param>

        /// <param name="innerException">Inner exception</param>

        public LoginException(String message, Exception innerException) : base(message, innerException)

        {

        }

        /// <summary>

        /// Argument constructor with serialization support

        /// </summary>

        /// <param name="info">Instance of SerializationInfo</param>

        /// <param name="context">Instance of StreamingContext</param>

        protected LoginException(SerializationInfo info, StreamingContext context) : base(info, context)

        {

        }

    }

Note the usage of the parameters in the constructor of the LoginException class and how the base class constructors are called. Also note how the last argument constructor in the LoginException class given earlier is used to provide support for serialization.

Using the LoginException class

The following code listing shows how you can use the LoginException class we just implemented.

static void Main(string[] args)

        {

            try

            {

                //Write code here to login the user.

                //If the provided credentials are invalid,

                //an exception object is thrown.

          throw new LoginException("Invalid credentials provided...");

            }

            catch(LoginException loginException)

            {

                //Write code here to handle the exception

                Console.WriteLine(loginException.Message);

            }

            Console.Read();

        }

Note that you should implement custom exception classes only if they are needed, i.e., you would like to add more functionality when working with exceptions in your applications.

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.