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!
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
An exception should be thrown when a function experiences a failure, i.e., an error. A function is a unit of work, and failures should be viewed as errors or otherwise based on their impact on functions.
If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw.
The calculate method should check for an exception and if there is no exception, return the calculated value to the main function i.e. v1+v2 or v1-v2; Else if an exception exists then it should print the error statement and the value that is returned from the calculate method to the main method should be 0.0(Not ...
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With