Ugrás a fő tartalomra

auto-document exceptions on methods in C#/.NET [closed]

I would like some tool, preferably one that plugs into VS 2008/2010, that will go through my methods and add XML comments about the possible exceptions they can throw. I don't want the <summary>or other XML tags to be generated for me because I'll fill those out myself, but it would be nice if even on private/protected methods I could see which exceptions could be thrown. Otherwise I find myself going through the methods and hovering on all the method calls within them to see the list of exceptions, then updating that method's <exception list to include those. Maybe a VS macro could do this?
From this:
private static string getConfigFilePath()
{
    return Path.Combine(Environment.CurrentDirectory, CONFIG_FILE);
}
To this:
/// <exception cref="System.ArgumentException"/>
/// <exception cref="System.ArgumentNullException"/>
/// <exception cref="System.IO.IOException"/>
/// <exception cref="System.IO.DirectoryNotFoundException"/>
/// <exception cref="System.Security.SecurityException"/>
private static string getConfigFilePath()
{
    return Path.Combine(Environment.CurrentDirectory, CONFIG_FILE);
}
Update: it seems like the tool would have to go through the methods recursively, e.g., method1 calls method2 which calls method3 which is documented as throwing NullReferenceException, so both method2 and method1 are documented by the tool as also throwing NullReferenceException. The tool would also need to eliminate duplicates, like if two calls within a method are documented as throwing DirectoryNotFoundException, the method would only list <exception cref="System.IO.DirectoryNotFoundException"/> once.

closed as off-topic by EJoshuaS, robinCTS, greg-449, DavidG, Chris Pickford Dec 22 '17 at 9:42

This question appears to be off-topic. The users who voted to close gave this specific reason:
  • "Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it." – EJoshuaS, robinCTS, greg-449, DavidG, Chris Pickford
If this question can be reworded to fit the rules in the help center, please edit the question.
  • 4
    Note that such a tool is not trivial and can never guarantee to give you a complete list of exceptions, because a) code my be executed dynamically, e.g. using reflection, or b) the exception is thrown by the runtime such as an OutOfMemoryException, StackOverflowException etc... – Dirk Vollmar Jun 7 '10 at 13:39 
  • 2
    Nor can this be exhaustive, as such a tool would have to both go through all the possible managed exception including those in the BCL and possibly know about the underlying com exceptions for code that does interop.– Oded Jun 7 '10 at 13:40
  • 2
    I'm curious as to why you want to do this. How would it make a difference to your calling code knowing or not knowing which exceptions might be thrown? – Christian Hayter Jun 7 '10 at 13:41
  • 5
    @Christian Hayter: It will be helpful to callers knowing what exceptions to expect. MSDN for instance documents this. – Dirk Vollmar Jun 7 '10 at 13:42
  • 1
    @FrustratedWithFormsDesigner: Strictly speaking, this is true of every (local, meaning no service references) .NET assembly. Even obfuscated IL could be analyzed (in fact, it could be analyzed without any additional difficulty) for exception handling. – Adam Robinson Jun 7 '10 at 14:08

4 Answers

The long and the short answer is that this isn't possible. Unlike Java, none of the .NET languages require that functions report a list of possible exceptions that can be thrown (which means that you either have to catch or report any exceptions that could be thrown on functions that it calls). Because of this, there's no generic way to determine an exhaustive list of every exception that a function could throw (I'm using the word function here to cover anything that's written like a function, including operators, constructors, etc.) because you have no guarantee as to the exceptions that could be thrown by what a given function might call.
If you're willing to go in limited, then it's conceivable that you could write something that could scan MSDN for the appropriate article for a given .NET library call and use the list of exceptions there (if any) to recursively establish a list of what could possibly be thrown. This wouldn't, however, cover any third-party libraries or catch any exceptions thrown by the runtime (OutOfMemoryException, StackOverflowException, NullReferenceException [unless you want to take it a step further and have your exception analysis also determine if there is any possibility of a null reference, but this, too, seems impossible to do in a completely generic sense]).
I'm pretty sure that this has been covered a time or two by the C# team (I'd be surprised if Eric Lippert hasn't already answered a question about this on SO), but I'm pretty certain that it boiled down to this: While this sort of system is useful and valuable to some people, mandating its use (and forcing you either to report or catch all possibly thrown exceptions) led to a lot of try { ... } catch (Exception ex) { ... } blocks in order to avoid the housekeeping, and blanket, silent catches are a lot worse (IMHO) than an unreported exception.
  • Is there a way of dynamically checking the list of exceptions in a method's XML comments? It'd be a cheap, non-exhaustive technique, but it'd be better than nothing/manually documenting exceptions. – Sarah VesselsJun 7 '10 at 13:49
  • @Sarah: There is no such tool that I'm aware of, but I can't see why you could write something to read the XML documentation files for a given library. You'll have to perform your own static analysis and overload resolution (matching the rules from the C# spec; calling this non-trivial would be a gross understatement) in order to match up calls with documentation. – Adam Robinson Jun 7 '10 at 13:50
  • 2
    The problem with checking recursively only on comments is that you don't know what exceptions the top method catch()es. So, if A calls B, and B can throw all sorts of exceptions, you don't know whether those bubble up, or if they are caught. Any kind of static analysis will be useless without knowing the exact underlying code. So, if you do this, don't bother looking recursively; you must trust that method A() will correctly document all possible exceptions it can throw. – drharris Jun 7 '10 at 13:54
  • 2
    One does not simply recursively check method comments. Their black XML is guarded by more than just catch blocks. There is evil there that does not sleep. – Sarah Vessels Jun 7 '10 at 13:58
  • 1
    The OP mentioned recursive analysis in the Update section. I merely wanted to point out that recursive analysis won't yield a proper indication of which exceptions bubble through without a very extensive algorithm (and IL access). And given XML comments only, you can't possibly know what bubbles through from called commands. It was a point of awareness, that any tool will not be 100% accurate. – drharris Jun 7 '10 at 15:27
You can achieve part of your requirements by using AtomineerUtils which has support for documenting exceptions.
You can also use GhostDoc, Resharper and Agent Johnson Plugin for generating exceptions. See the following question: How to document thrown exceptions in c#/.net
Exception Hunter from RedGate software will get you half-way there. It can do a static analysis of your code and show you what exceptions will be thrown by what lines of code -- including .NET Framework calls. It won't write the XML documentation for you.
But, I have to say, you need to be realistic about how useful such a tool would be... there are a number of exceptions that may happen as a result of extremely unusual circumstances, such as System.OutOfMemoryException and System.ExecutionEngineException, or as a result of programmer error, such as System.NotImplementedException. Technically, these are all possible, but realistically, attempting to document most of them for every method is not worth your time... you'd end up with hundreds of lines of comment for practically every method in your application.
RedGate Exception Hunter does analyze code for possible exception. Maybe you could use some of its functionality.

Megjegyzések

Népszerű bejegyzések ezen a blogon

SW Documentation: Requirements

Requirements Nonfunctional Requirements Q&A FEBRUARY 17, 2010  ~  ANDREW STELLMAN ~  3 COMMENTS Non-functional requirements Q&A: We answer questions from readers about using  nonfunctional requirements  on a real software project, and how to use them on a real software project. Non-functional requirements: Planning out how well your software will work A couple of months ago I wrote a post called  Using nonfunctional requirements to build better software . It’s basically a step-by-step guide for creating an easy, practical technique to use nonfunctional requirements on a real software project, treating them in a way that’s similar to how a lot of Agile teams treat user stories, scenarios and other functional requirements: by sticking them on index cards and using them to do some lightweight planning. Since then, I’ve gotten a lot of questions about nonfunctional requirements (or, as some people call them, non functional requirements...

Privacy Notice for Visitors to Our Users’ Sites

Privacy Notice for Visitors to Our Users’ Sites Sections Who’s Who and What This Privacy Notice Covers Information We Collect About Visitors to Our Users’ Sites Information a Visitor Provides to a Site Information We Automatically Collect from the Site Other Information Provided by Our Users How We Use Visitor Information How We Share Visitor Information Other Tools Other Resources Hi there! This Privacy Notice explains how we, at Automattic, process information about the visitors of our users’ websites in connection with the services we provide through WordPress.com, Jetpack (including WooCommerce Services), IntenseDebate, Polldaddy.com, and Akismet. Read on! Who’s Who and What This Privacy Notice Covers Let’s talk first about who we are at Automattic, what we do, and what this Privacy Notice covers. We are the folks behind a variety of products and services designed to allow anyone–from bloggers, to small business owners, and enterprises–to create, publ...

THE RIGHT WAY TO WRITE A SINGLETON

THE RIGHT WAY TO WRITE A SINGLETON July 17, 2015 by   Hector Matos Even though I've written about the woes of managing state in my previous post, sometimes there's just no way we can avoid it. One example of managing state is something we're all quite acquainted with - The Singleton. The problem we find in Swift is that there are SEVERAL ways of implementing them. But which way is the right way? In this post I'm going to show you the history of the singleton and then show you the right way to implement the singleton in Swift. If you want to see the right way to implement the singleton pattern in Swift along with proof of it's "right-ness", you can scroll to the bottom of the post and see it there. :) A TRIP DOWN MEMORY LANE Swift is a natural evolution of Objective-C. In Objective-C, this is how we implemented the singleton: @interface Kraken : NSObject @end @implementation Kraken + ( instancetype ) sharedInstance { ...