Reputation: 13673
Using XML comments in C#, I can document that a method may throw an exception:
<exception cref="FooException">Thrown if foo is invalid.</exception>
However, if a method has no exception
tag in its XML documentation, this may mean one of two things:
exception
tag.In my experience, the second is usually the case. The question is, then:
How do I explicitly document that a method will never throw an exception?
The best I've come up with so far is to simply mention it in the method's summary
, like "This method does not throw exceptions". But I was wondering if there is a more formal way to express this, like throw()
in C++ (even though that may be a bad example).
Upvotes: 9
Views: 1105
Reputation: 38967
Adding it in the summary is good for documentation and communication with other developers.
You said you want to have a more formal way, tough.
From what I know of C# (very little), Exception
has two main child classes, ApplicationException
and SystemException
. You generally can't guarantee that a system exception won't be thrown. We may however guarantee that no ApplicationException
is ever thrown.
With code contracts, you may use EnsuresOnThrow
post-conditions:
Contract.EnsuresOnThrow<ApplicationException>( false );
Wrap the body of your code in a global try/catch
, and assert False
in the catch block.
In both cases, a static analyzer should understand that the assertion or post-condition can never be true when an exception occurs: thus, the application fullfills its contracts if and only if no exception is ever thrown from your function.
Upvotes: 2