Daniel Wolf
Daniel Wolf

Reputation: 13673

How to explicitly document that a method does not throw exceptions

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:

  1. The author thoroughly tested the method, has made sure it will never throw an exception, and wants to document this fact by not adding an exception tag.
  2. The author didn't care about documenting exceptions, so this method may throw anything.

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

Answers (1)

coredump
coredump

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.

1. With contracts

With code contracts, you may use EnsuresOnThrow post-conditions:

    Contract.EnsuresOnThrow<ApplicationException>( false );

2. Without contracts

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

Related Questions