Let's assume we have a method handling operations in a tree hierarchical data structure located in a class handling such a structure.
Let's look closer at one of those methods:
void MoveNode(Node currentNode, Node newParentNode)
{
/* check if new parent isn't current's child already */
if (newParentNode.LMargin < currentNode.LMargin && newParentNode.RMargin > currentNode.RMargin)
{
//DO WORK
}
else throw new ArgumentException("New parent node cannot be current's own child");
}
MSDN states: do not throw Exceptions to control the flow !
My question: is this use of ArgumentException alright in your opinion, or would you use some kind of a return value. If so, how would you supply the error/validation message.
Since the exception being thrown indicates a bug here, and it thus won't be ever thrown in a correctly working program and exception is the right choice.
What you should not do is:
try
{
MoveNode(...)
//Do something
}
catch(ArgumentException e)
{
//Do something else
}
In that example you expect the exception being thrown regularly and use it to control the control flow. Catching an ArgumentException
in the caller is almost always a bad idea. This kind of exception should only be caught in the top-level handler, if at all.
Personally I don't like you throwing the exception in the else clause. I prefer doing my parameter checking at the beginning of the function and throw the exception immediately afterwards. That prevents nesting the non error code within multiple if blocks.
There are three types of exceptions
Eric Lippert talk about these kinds of exception in a blog entry: Vexing exceptions
When to use the third kind of exception, and when to use return values is a judgment call.
I don't think this is the case of "not to use exception for control the flow".
This is argument validation. The method cannot work input parameters aren't valid, so, using an exception is the best way to tell the caller that it's trying to do a bad business.
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