burnt1ce
burnt1ce

Reputation: 14917

How to make it clear that a method can throw an exception?

One of the methods that I'm creating throws an exception. What's the clearest way of showing (either in code or comments) that my method could throw an exception and therefore a try{} and catch{} needs to be applied to my method.

Thanks!

Upvotes: 6

Views: 199

Answers (3)

Andrew Hare
Andrew Hare

Reputation: 351698

Use an <exception/> tag in your method's documentation comments:

/// <summary>Does Foo</summary>
/// <exception cref="System.ArgumentNullException">
/// Thrown when bar is null.
/// </exception>
public void Foo(Bar bar) 
{ 

}

One of the nice things about using the <exception/> tag is that Visual Studio will include this information in the method information tooltip like this:

Upvotes: 24

John Fisher
John Fisher

Reputation: 22717

Sadly, clarity isn't the only issue. Otherwise, you could do this:

public void Method_MayThrowException() {
  ..
}

Since that is undesirable for other reasons, a comment that can be picked up by intellisense is likely to work the best.

Also, if you're open to add-ons or process modifications, you can read about Spec#. Or you could implement FxCop rules.

Upvotes: 1

DeusAduro
DeusAduro

Reputation: 6076

In all of the MSDN documentation, every method shows what it may throw. I like this idea and thus in my comments I do something like:

// throws: MyDangerousError, StupidProgrammerError

If you want to go into more detail you can explain in what situations each error is thrown, often though the error name is enough to give users an Idea.

Upvotes: 1

Related Questions