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).
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 ...
To specify that writeList can throw two exceptions, add a throws clause to the method declaration for the writeList method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method.
The throws keyword is used to declare which exceptions can be thrown from a method, while the throw keyword is used to explicitly throw an exception within a method or block of code. The throws keyword is used in a method signature and declares which exceptions can be thrown from a method.
When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.
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.
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