FxCop-compliant Exceptions (Code Snippets vs. Item Templates)

Mr Haack posted recently about a topic near and dear to my heart: inheriting from Exception. To keep FxCop quiet, there is a surprising amount of code to write when creating your own exception types, as Phil notes: make it serializable, implement four constructors, etc. It can be tedious to do that every time you create your own exception. So, code generation is definitely the way to go, however, this is where I must respectfully part ways with Phil.

After playing with both code snippets and item templates, I find item templates to be a superior method for class-level code generation. Unfortunately, in all the betas of VS 2005 I’ve tried, there is no easy way to generate an item template easily (File -> Export Template never works, although I’ve not used any of the CTPs). I’ve outlined how to do it for beta 1 in a previous article. There are very few differences with Beta 2 and hopefully RTM (elements became attributes in the vstemplate file). Then creating a new FxCop-compliant Exception class is as easy as adding any class file to a project. On the other hand, a code snippet requires a file to already exist and if you’re abiding by the Microsoft’s guidelines of one public type per file (you are, right?), then you have to do all that work up front.

But the above advice is essentially useless for everyone: VS 2005 isn’t out yet (but it’s close)! Wouldn’t it be great to get this with Visual Studio 2003? Well, you can’t by default: that’s one of the reasons VS2005 is so compelling. However, there are third party tools to help you. Before it became not free, CodeSmith allowed you to generate code at the file level, so I whipped up this template file for all my Exception building needs. Just run it in CodeSmith (v2.x if you’re lucky (and cheap)). Of course, there is the way Phil does it as well. Your mileage may vary.

Download the CodeSmith FxCopException.cst template.

To be really nice to all 3 readers at jasonkemp.ca, I also whipped up an FxCopException item template for VS 2005. Aren’t I sweet? Just drop it in My Documents\Visual Studio 2005\Templates\ItemTemplates\

Download the FxCopException Item Template for VB
Download the FxCopException Item Template for C#

One Reply to “FxCop-compliant Exceptions (Code Snippets vs. Item Templates)”

Comments are closed.