.NET Tip: Throwing Custom Exceptions

Creating your own custom exceptions is very easy and allows your code to be more explicit as well as being able to provide more user-friendly error messages. To show how to use custom exceptions, I will use connecting to a database as an example. Connecting to a database is something your application probably does on a regular basis and is a common point of failure. The first step is to create the class for your custom exception that inherits from another exception class. In this case, you’ll create an UnableToOpenDatabaseException based on the Exception class. Here is what the custom exception class looks like:

public class UnableToOpenDatabaseException : Exception
{
   public UnableToOpenDatabaseException()
      : base()
   {
   }

   public UnableToOpenDatabaseException(string Message)
      : base(Message)
   {
   }

   public UnableToOpenDatabaseException(string Message,
                                        Exception InnerException)
      : base(Message, InnerException)
   {
   }

   protected UnableToOpenDatabaseException(SerializationInfo Info,
                                           StreamingContext Context)
      : base(Info, Context)
   {
   }
}

To use the custom exception, you need to check to see whether an exception is thrown when you attempt to connect to the database. In my case, I’m connecting to SQLServer, so I will check to see if a SQLException was thrown. If a SQLException is thrown, I throw the new UnableToOpenDatabaseException, passing the original exception to the new one. If an exception other than a SQLException is thrown, I simply rethrow the original exception.

using (SqlConnection CN =
   new SqlConnection("*** Your connection string here ***"))
{
   try
   {
      CN.Open();
   }
   catch (SqlException ex)
   {
      // Throw the custom UnableToOpenDatabaseException
      throw new UnableToOpenDatabaseException("Unable to open
         database connection.", ex);
   }
   catch (Exception ex)
   {
      // Rethrow the original exception
      throw;
   }
}

This allows the calling code to take advantage of the new exception while still allowing it to access all of the original exception information if needed. This example lumped any type of SQLException under the new exception type. If you needed more granularity in your exceptions, you could create custom exceptions for different failure conditions.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read