joydip_kanjilal
Contributor

How to implement a custom exception class in C#

how-to
Nov 20, 20174 mins
C#Small and Medium BusinessSoftware Development

Take advantage of custom exception classes to extend error handling or add meaningful information to the errors thrown by your .Net applications

An exception is an error that occurs at runtime and terminates the normal flow of execution of a program if not handled properly. 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 add clear, meaningful, and user-friendly information to exceptions when errors occur while your program is running.

The base class for all exceptions in .Net is Exception. All of the 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 in .Net.

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 from ApplicationException. ApplicationException was originally intended to be used to create user defined exceptions, but using it is no longer recommended. As Microsoft’s documentation states

You should derive custom exceptions from the Exception class rather than the ApplicationException class. You should not throw an ApplicationException exception in your code, and you should not catch an ApplicationException exception unless you intend to re-throw the original exception.

The reason ApplicationException has been deprecated is that using it unnecessarily extends the exception hierarchy. Although the ApplicationException class extends the Exception class, it does not add new functionality. Its only purpose was to provide a way to distinguish between exceptions defined by applications and exceptions defined by the system.  

Designing a custom exception class

Let’s now dig into some code. The following code snippet shows 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 will create a custom exception class named LoginException, which can be used to trap errors that might occur when a user logs in to the system, e.g., if the user credentials are incorrect.

public class LoginException : System.Exception
    {
       //TODO
    }

The following code listing shows our custom exception class 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 is used to provide support for serialization.

Using a custom exception 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 when you want to add more functionality to the exception handling in your applications, or when it makes sense to give the user additional information. In most cases, you will want to rely on the standard exceptions .Net gives you.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author