Dan Appleman

Subscribe to Dan Appleman: eMailAlertsEmail Alerts
Get Dan Appleman via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


INETA's Topic Choice: How to Handle Exceptions with Class

Defining custom exceptions

By now most of you reading this article will be familiar with .NET exception handling, at least in its basic form. You know how to catch exceptions using Try...Catch blocks. You know how to handle exceptions raised by the framework. You may even have created and thrown your own exceptions.

In this article you'll learn how to take this to the next level - how to define custom exceptions for your own classes and components, and the design patterns that you should use when doing so.

I have included two sample projects to help explain these design patterns. The SampleComponent project contains the MyComponent component, which raises a variety of exceptions. The project also includes a couple of custom exception classes that you'll learn about later in this article. The component represents any generic component or reusable class.

If you have no interest in components or code reuse, you really don't need to read this article - just keep throwing System.Exception objects (you have more important things to learn than what I have to say here).

The SampleComponentTest project represents a generic client application that uses a component.

The ApplicationException Class
It all begins with the following remark in Microsoft's documentation for the System.ApplicationException class:

ApplicationException is thrown by a user program, not by the common language runtime. If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception, but does not add new functionality. This exception is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system.

As is often the case with Microsoft documentation, a short paragraph has far-reaching implications that tend to be a bit on the obscure side. Consider what this paragraph implies:

  1. You should avoid throwing system exceptions.
  2. If you create custom exceptions, they should derive from ApplicationException.
  3. There is reason to differentiate between exceptions thrown by the system and those thrown by the framework.
This implies that you should never use the following code, found in the MyComponent class:

    Public Function SimpleTest1()
      As String
        Throw New Exception ("Here is an exception in SimpleTest1")
End Function

Perhaps the solution then is to use code like this:

Public Function SimpleTest2() 
    As String
    Throw New ApplicationException( _
    "Here is an exception in SimpleTest2")
End Function

This is acceptable but still not perfect. The ApplicationException documentation also remarks:

In most scenarios, instances of this class should not be thrown. In cases where this class is instantiated, a human-readable message describing the error should be passed to the constructor.

It's apparent that Microsoft's intent is that developers create their own custom exceptions. But why?

Custom Exceptions and Classes
Think of the .NET Framework itself as your guide. What is the framework if not a set of reusable classes? How does Microsoft raise exceptions in the framework? They don't raise generic System. Exception objects. If you look at the documentation for the various classes in the framework, you'll see that each one documents the exceptions that it might raise. Namespaces define custom exceptions used by classes in that namespace. For example, classes in the System.IO namespace often raise System.IOException errors.

Why use this approach? Obviously, it allows for more flexible error handling, such as that shown in the ExceptionButtons_ Click method of the SampleComponentTest project (see Listing 1).

As you can see, you can build a list of Catch terms to provide handling according to the exception type. Most developers are familiar with this approach - but there's another for use with custom exceptions.

When you design a class or component, it is important to define the exceptions that it can raise. But you can't just allow framework exceptions to propagate outward from your component; you might change something in your code, or Microsoft might change a framework class in such a way that your component will end up raising exceptions that are not part of your original definition.

Instead, you should catch all errors that might occur in your component and throw your own custom error for the class. By the way, that's what the InnerExcep-tion property of the System.Ex-ception class is for. When you throw your custom exception, you set the inner exception to the originating exception so clients of your component or class can obtain information about the original cause of the problem.

Creating Custom Exceptions
The MyExceptionType1 class (see Listing 2) demonstrates how you might create your own class that derives from ApplicationException. The class also extends the base class by capturing additional information - in this case an ExceptionType enumeration that describes the cause of the exception.

MyExceptionType1 is a workable class, but if you're designing a component for reuse you should follow Microsoft's example just a bit further and provide for localization.

MyExceptionType2 (see Listing 3) demonstrates a number of interesting features. The Errors.resx file contains the “localized” strings. This file is embedded in the component, and represents the default (neutral) strings. You can add satellite assemblies to the component for different locales - even distributing them after the fact to add additional language support. The exception class caches the resource manager, loading it only on first use, then holding a reference for future use. Access to the resource manager is synchronized on an object in order to make sure that the exceptions will work correctly with multithreaded clients.

In this example, if the string does not match a key in the resource file, the original string is considered the message. This is arguably an error condition, but since the whole point is to throw the original exception, it makes little sense to throw a missing resource exception instead. However, you might want to report this condition to the debugger to help track down missing strings.

The MyExceptionType2 class also provides constructors that allow you to incorporate parameters into the localized string and to report inner exceptions.

The class is also marked as serializable. This makes it possible for exceptions to be passed as parameters and return values on remote components. If you do plan to use it with remote components, consider placing your exception classes in their own assembly to make it easy to support them on both the server and client sides.

The SampleComponent and SampleComponentTest projects demonstrate the raising and catching of various exceptions. The design patterns shown here are very similar to those that Microsoft uses within the .NET Framework.

It may seem like a lot of extra effort, but it really isn't. In fact, the samples contain most of the code you'll need. And the extra effort to properly design the exception side of your object model will pay off in the long run in terms of long-term stability and reliability - and will save you a great deal of effort should you decide at a later date to localize your components or classes.

More Stories By Dan Appleman

Daniel Appleman is president of Desaware, Inc., a developer of add-on products and components for Microsoft Visual Studio. He is a cofounder of Apress, and the author of numerous books, including Moving to VB.NET: Strategies, Concepts and Code; How Computer Programming Works; Dan Appleman's Visual Basic Programmer's Guide to the Win32 API; Always Use Protection: A Teen's Guide to Safe Computing, and a series of e-books on various technology and security topics. (A complete list can be found at www.desaware.com.)

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.