This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Visual Studio
VS 2005+

Visual Studio Exception Code Snippet

When you are creating a custom exception class, there are several constructors that you should provide in addition to the default, parameter-less constructor. To quickly create code for these constructors, you can use a Visual Studio code snippet.

Code Snippets

Code snippets were introduced in Visual Studio 2005. They allow a short name, or alias, to be typed into a program's source code. The alias is then automatically expanded into some usable code. This can speed up the creation of standard structures, such as the definition for a custom exception type.

The Exception Snippet

When you are creating a custom exception class, you should include four standard constructors. These are in addition to any further constructors that you wish to define. Three of the standard constructors are public. These allow the creation of a new exception with no parameters, the instantiation of an exception with a message specified and the generation of an exception with both a message and an inner exception. The fourth constructor is protected rather than public. It is used when an exception is created from serialised data.

Visual Studio provides a code snippet that automatically inserts the definitions for the four constructors, in addition to some comments. The comments provide the URLs of web pages that explain some exception handling guidelines. To use the code snippet, position the text cursor within the code block of a namespace, class or structure. Type the word "exception" and press the Tab key twice. Code similar to the following will appear. NB: The comments have been removed.

public class MyException : Exception
    public MyException() { }
    public MyException(string message) : base(message) { }
    public MyException(string message, Exception inner) : base(message, inner) { }
    protected MyException(
      System.Runtime.Serialization.SerializationInfo info,
      System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }

When the boilerplate code is inserted, the "My" prefix for the class name is highlighted. If you overtype this text with a new prefix for your exception, all of the constructor signatures are updated accordingly. Pressing the Tab key again highlights the "Exception" base class name so that you can quickly replace this with another exception type, if required.

10 August 2009