Writing Custom Exceptions Using Resharper Live Templates

0 comments suggest edit

Writing proper custom exceptions can amount to a lot of busy work. Oh sure, it’s easy to simply inherit from System.Exception and stop there. But try running that baby through FxCop or passing that exception across AppDomains and you’re in for a world of hurt (hyperbole alert!).

What makes writing a custom exception a pain? First, there are all those constructors you have to implement. You also need to remember to mark the class with the Serializable attribute. Also, if your exception has at least one custom property, then you’ll want to implement ISerializable, a special serialization constructor, and more constructors that accept the new property.

On page 411 of Applied .NET Framework Programming, Jeffrey Richter outlines the steps to write a proper custom exception class.

If you have this book, you should definitely read and learn these steps. Or if you are a ReSharper user, you can be lazy and just use the Live Template (akin to a Whidbey Code Snippet) I’ve created and posted here for your exceptional enjoyment.

Unfortunately, I do not know of any way to export and import live templates within ReSharper, so you’ll have to follow the steps I outlined in a previous post.

I have included two templates. The first is for a full-blown sealed custom exception with a single custom property. It’s easy enough to add more properties if you need them. The second is for a simple custom exception with no custom properties. The ReadMe.txt file included outlines a couple of settings you need to make for a couple template variables.

I ended up using the abbreviation excc to expand the full exception class and excs for the simple exception class. This ought to save you a lot of typing. Below is a screenshot of the full template…

Exception Live
Template

Found a typo or error? Suggest an edit! If accepted, your contribution is listed automatically here.

Comments

avatar

3 responses

  1. Avatar for Terry Thibodeau's Blog
    Terry Thibodeau's Blog February 14th, 2007

    When I started using Resharper , one of the first things I did was to go online and do a quick search

  2. Avatar for Robert
    Robert November 5th, 2007

    I did download the zip file with the templates but the SimpleExceptionTemplate have an error in it. There are two constructors that take one string as an argument so I guess the last constructor should look like this:
    protected $TYPE$Exception(SerializationInfo info, StreamingContext context) : base(info, context)
    {}

  3. Avatar for Leszek Salford
    Leszek Salford April 9th, 2018

    11 years... and still on net.
    SimpleExceptionTemplate contains code duplication.