My Links

Archives

Knowing Exceptions Up Front (from: Dave Donaldson)

Having written some Java in the past, one of the things I really liked about the language was that you can list which exceptions your method might throw in the method declaration, as such:

public void DoSomething(...) throws ExceptionType1, ExceptionType2 {}

I always felt this was good practice because anyone using your API would know right up front what type of exceptions they might run into when calling your methods. This language feature is something I wish C# and VB.NET had.

So that begs the question: In .NET, how do you let users of your API know what exceptions they can trap for when invoking your methods? The answer is not a language feature, but an IDE feature - use the XML comments (sticking with C# for the remainder of this post).

The XML comments exposes an <exception> tag. The <exception> tag has an attribute named cref, which is where you enter the exception type. Then between its opening and closing tags you supply a description. A sample might look like so:

/// <summary>
/// This method opens the file and does stuff.
/// </summary>
/// <param name="file">File to open and read.</param>
/// <returns>Something</returns>
/// <exception cref="System.IO.FileNotFoundException">Occurs when the file is not found.</exception>

At this point, once you generate the documentation for your code, anyone looking at your stuff will see that for the above method, they can expect a FileNotFoundException if the file they supply to the method is not found (obviously). And you're not limited to the number of <exception> tags you can list, so be sure to list all possible exceptions that you might throw.

I mean, think about it. How many times have you used a class library, invoked a method, and got an exception of a type you didn't trap for in your try...catch block? So then you gotta open your code, add another catch statement, then test, build, and redeploy. If you had known the list of possible exceptions beforehand, you would have coded for it and tested it way before it was found by a user in production.

So if you're not abiding by this best practice, start. It will save you, and the other developers who use your code, time in the end.

posted on Monday, January 10, 2005 12:33 PM

sales@tourneylogic.com Copyright © Tourney Logic