How to document all exceptions a function might throw?

Fundamentally, what you ask is impossible in virtually every real-world situation.

There are two parts to documenting thrown exceptions.

1) The easy bit. Document the exceptions that are directly thrown in your method. You can do this by hand, but it’s pretty laborious and if you fail to keep the docs in sync wiht the code the documentation becomes misleading (potentially worse than having no documentation at all, as you can only really trust documentation that you’re sure is 100% accurate). My AtomineerUtils add-in makes this much easier to achieve, as it keeps the code and doc comments in sync with a minimum of effort.

2) The impossible bit. Document all exceptions that might “pass through” your method. This means recursing through the entire subtree of methods called by your method to see what they might throw. Why is it impossible? Well, in the simplest cases you will be statically binding to known methods, and can therefore scan them to see what they throw – moderately easy. But the majority of cases ultimately call dynamically bound methods (e.g. virtual methods, reflected or COM interfaces, external library methods in dlls, operating system APIs, etc) for which you cannot definitively work out what might be thrown (as you won’t know what is called until you actually run the program on the end-user’s PC – every PC is different, and the code executed on (e.g.) WinXP and Win7 could be quite different. Or imagine you call a virtual method and then somebody adds a plug-in to your program that overrides the method and throws a new type of exception). The only way to reliably handle this situation is to catch all exceptions in your method, and then re-throw specific ones that can then be documented precisely – if you can’t do this, then documentation of exceptions is pretty much restricted to “commonly thrown and typically expected exceptions” in your method, leaving “exceptional errors” to be left largely undocumented and simply passed up to a higher level unhandled-exception catch blocks. (It is this horrible “undefined” behaviour of exceptions that often leads to the necessity of using catch(…) – academically it is “evil”, but if you want your program to be bullet proof, you sometimes have to use catch-alls to be sure that unexpected situations don’t assassinate your application).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)