in Development

Xml Documentation Comments – Exceptions I

Long time ago my team was investigating about a new beta technology called .NET, we needed to compare it against Java and decide what would be our new development platform (I guess it’s clear which one we successfully decided to use). One of the things I liked about Java were Checked Exceptions, I thought it was handy to have this enforced by the compiler. Nowadays I’m 100% convinced I wouldn’t like to have them in .NET and it seems I’m not the only one. If you are curious to know why checked exceptions where not added to .NET you can read the interview done to Anders Hejlsberg some years after the beta release.

In any case, it’s clear that even if we do not want the compiler forces us to handle exceptions, there is no doubt that the information about the exceptions that can be thrown by a method are very useful for developers. In order to help us with this we can make use of the Xml Documentation Comments, to do it we have the exception tag that allow us introducing the information regarding the exceptions  thrown by our Constructors, Methods, Properties and Indexers, this information will then be listed not only in the documentation we generate with tools like Sandcastle or NDoc  but also when we use Intellisense.

Below you can see an example about how to make use of it.

/// <summary>
/// Does something
/// </summary>
/// <param name="value">A string value</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when value is null
/// </exception>
public void DoSomething(string value)
    if (value == null)
        throw new System.ArgumentNullException("value");

The compiler gives us some help to make sure we write the Xml comments, but unfortunately it is not enabled by default. To do it we need to go to the build properties of our project and configure it to generate the documentation files.

xml documentation file

After we configure it the compiler will generate errors (warnings if you do not work with “Treat warnings as errors”, but I like to think nobody has this option disabled in professional software) for the public or visible elements that do not have the Xml comments. This is a good start point, the compiler validates the Xml comments exist, but does not check the validity of them. i.e. somebody can add the tags and let the values empty. Therefore if we want to check our documentation is properly formatted we need to look for static analysis tools that do this work.

In the next part of this post we will see how to create a custom rule for StyleCop that checks the exceptions thrown by our code are documented.

Write a Comment