I am currently writing a small framework that will be used internally by other developers within the company.
I want to provide good Intellisense information, but I am not sure how to document thrown exceptions.
In the following example:
public void MyMethod1()
{
MyMethod2();
// also may throw InvalidOperationException
}
public void MyMethod2()
{
System.IO.File.Open(somepath...); // this may throw FileNotFoundException
// also may throw DivideByZeroException
}
I know the markup for documenting exceptions is:
/// <exception cref="SomeException">when things go wrong.</exception>
What I don't understand is how to document exceptions thrown by code called by MyMethod1()
?
MyMethod2()
File.Open()
?What would be the best way to document possible exceptions?
You should document every exception that might be thrown by your code, including those in any methods that you might call.
If the list gets a bit big, you might want to create your own exception type. Catch all the ones you might encounter within your method, wrap them in your exception, and throw that.
Another place you might want to do it this way is if your method is on the face of your API. Just like a facade simplifies multiple interfaces into a single interface, your API should simplify multiple exceptions into a single exception. Makes using your code easier for callers.
To answer some of Andrew's concerns (from the comments), there are three types of exceptions: Ones you don't know about, ones you know about and can't do anything about, and ones you know about and can do something about.
The ones you don't know about you want to let go. Its the principal of failing fast--better your app to crash than enter a state where you might end up corrupting your data. The crash will tell you about what happened and why, which may help move that exception out of the "ones you don't know about" list.
The ones you know about and can't do anything about are exceptions like OutOfMemoryExceptions. In extreme cases you might want to handle exceptions like this, but unless you have some pretty remarkable requirements you treat them like the first category--let 'em go. Do you have to document these exceptions? You'd look pretty foolish documenting OOMs on every single method that new-s up an object.
The ones you know about and can do something about are the ones you should be documenting and wrapping.
You can find some more guidelines on exception handling here.