views:

169

answers:

2

As a good programmer and code reviewer, I am always cringing when I see a developer catch "Exception". I was going to suggest C# add the "throws" clause from Java, but after reading the Anders Hejlsberg interview (http://www.artima.com/intv/handcuffs.html) I see why it is not there.

Instead, I would like to suggest the canthrow statement. The canthrow statement would have the following properties

  1. canthrow statement would be declared on the method and list the exceptions that this method throws.
  2. canthrow would report to the calling methods or intellisense the exceptions that can be thrown, as well as any exceptions that a called method could throw and are not handled locally.
  3. canthrow is not contractual, so versioning is not a problem.

The idea here is that most developers want to catch and handle the proper exceptions, but they simply don't know what they are. If we have a way to inspect the methods a design time, developers will be more likely to add and handle the exceptions that are relevant and let the unhandled exceptions bubble up.

Now as final thought, you probably can say that this could all be done by Intellisense using reflection, but that would return every and all exception possible. The canthrow would be allow the library developer to emphasize the exceptions that are expected to be handled by the callers.

What do you think?

+1  A: 

I'm not sure what it buys you above documentation, since the method generally can't guarantee not throwing other exceptions. For example, consider the case where a thread gets aborted.

Steven Sudit
+8  A: 

This is already available to some extent in the form of the <exception> documentation comment tag. It would be possible to dig deeper by examining the call tree using something like FxCop introspection, but once virtual methods are involved it might get messy quickly.

As for editor integration, you might have better luck asking for something like this in Resharper than you would trying to get support for it in Visual Studio itself.

Jeffrey Hantin