Wrapping Exceptions 

To wrap an exception, you specify it as the inner exception of a new exception and then throw the new exception. This practice should be used only in situations where the original exception is not meaningful to the person who receives the exception, or the call stack for the exception is misleading or uninteresting. For example, consider a library that provides functionality for managing XML-based configuration files. Internally, the configuration file manager uses an XML reader to read files. If a configuration file is incorrectly formatted, the XML reader could throw an exception that includes a message and call stack details for the XML reader and its supporting types, which are meaningless to the application user. In this scenario it is appropriate for the configuration file manager to wrap the XML reader exception and re-throw a new exception that indicates the true nature of the problem.

The following guidelines help ensure that you wrap exceptions correctly and only when appropriate.

Consider wrapping specific exceptions thrown from a lower layer in a more appropriate exception, if the lower layer exception does not make sense in the context of the higher-layer operation.

This should be done rarely because it makes debugging more difficult. It is appropriate when you are certain that the lower layer is never the true source of the error.

Avoid catching and wrapping non-specific exceptions.

This practice should be avoided because it hides errors. Exceptions to this rule include cases where the wrapper exception communicates a severe condition that is much more interesting to the caller than the actual type of the original exception. For example, the TypeInitializationException exception wraps all exceptions thrown from static constructors.

Do specify the inner exception when wrapping exceptions.

This allows tools to display the underlying details of the problem and can aid in debugging code. The following code example demonstrates wrapping an exception.

public void SendMessages()
{
    try 
    {  
        EstablishConnection();
    }
    catch (System.Net.Sockets.SocketException e)
    {
        throw new CommunicationFailureException(
            "Cannot access remote computer.",
            e);
    }
}

Portions Copyright 2005 Microsoft Corporation. All rights reserved.

Portions Copyright Addison-Wesley Corporation. All rights reserved.

For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.

See Also

Concepts

Exception Throwing

Other Resources

Design Guidelines for Developing Class Libraries
Design Guidelines for Exceptions