Writing Custom Exception Classes the Quick Way


Until recently I thought this was a well-known feature. After demonstrating it a few times, I found out it wasn’t.

A long time ago, in an cubicle far, far away, someone created the .Net Framework. To cut a long story short, they simultaneously produced guidelines for creating Exception classes, which you should always use or face having your fingernails pulled out with a staple-gun.

The guidelines state:

“Use the common constructors shown in the following code example when creating exception classes. “

[C#]

public class XxxException : ApplicationException
{
public XxxException() {… }
public XxxException(string message) {… }
public XxxException(string message, Exception inner) {… }
public XxxException(SerializationInfo info, StreamingContext context) {…}
}


If you don’t believe me, you can look here:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp

Now, I don’t know about you, but I can’t remember all that every time I create a custom exception class. Maybe that’s why the guidelines also state:

In most cases, use the predefined exception types. Only define new exception types for programmatic scenarios, where you expect users of your class library to catch exceptions of this new type and perform a programmatic action based on the exception type itself.

But let’s ignore that. It’s not relevant.

So, did you know that there is a Visual Studio code snippet that does the work for you? Here’s how you use it.

  1. Create a new class.
  2. inside the namespace definition of the new class, type
    Exception

  3. Press the tab key twice.

You then get the following code, free of charge:

[global::System.Serializable]
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) { }
}

What’s more, you get code snippet functionality which automatically changes the names of all the constructors when you change the name of the class.

I wonder what other code snippets are available. Do you know of any cool ones? What are your favorites?

  • Hi Richard,

    my favorites are propa and propdp. In a C#-Project created with Visual Studio 2008 these new snippets create the functionality for attached and dependency properties.

    Thomas

  • My code doesn’t throw exceptions, hence I don’t write any :)

You can follow any responses to this entry through the RSS 2.0 feed.