Consider this code (Java, specifically):
public int doSomething() { doA(); try { doB(); } catch (MyException e) { return ERROR; } doC(); return SUCCESS; }
Where doB() is defined as:
private void doB() throws MyException
Basically, MyException exists only in case doB() meets some condition (which is not catastrophic, but does need to somehow raise this condition) so that doSomething() will know to exit with an error.
Do you find the use of an exception, in this case to control flow, acceptable? Or is this a code smell? If so, how would you refactor this?
It entirely depends on what that error condition is, and what the method’s job is. If returning
ERRORis a valid way of handling that error for the calling function, why would it be bad?Often, however, it is a smell. Consider this:
That is a very big code smell, because you don’t expect a double value. You just want to know whether a string contains a double.
Sometimes, the framework you use doesn’t have other ways of doing what you want. For the above, there is a better way:
Those kinds of exceptions have a special name, coined by someone whose blog I read recently, but sadly, I forgot its name. Please comment if you know it. Last but not least, the above is pseudocode. I’m not a C# developer so the above doesn’t compile, I’m sure, but
TryParseInt32/ParseInt32demonstrates that well I think, so I’m going with C#.Now, to your code. Let’s inspect two functions. One smells, and the other doesn’t:
1. Smell
That’s a code smell, because when you want to setup a system, you don’t want it to fail. Failing to setup a system means you can’t continue without handling that error.
2. OK
That is OK, because the purpose of that method is to test whether the workstation is still reachable. If it’s not, then that is part of the result of that method, and not an exceptional case that needs an alternative return path.