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?
If you use exceptions for the control flow, it may cause performance issues and your code may be less readable. Hope this helps!
Flow reports applications errors by throwing specific exceptions. Exceptions are structured in a hierarchy which is based on base exception classes for each component. By default, PHP catchable errors, warnings and notices are automatically converted into exceptions in order to simplify the error handling.
The method to choose depends on how often you expect the event to occur. Use exception handling if the event doesn't occur very often, that is, if the event is truly exceptional and indicates an error (such as an unexpected end-of-file). When you use exception handling, less code is executed in normal conditions.
Is it really important for doC() to be executed when doB() fails? If not, why not simply let the Exception propagate up the stack to where it can be handled effectively. Personally, I consider using error codes a code smell.
Edit: In your comment, you have described exactly the scenarion where you should simply declare
public void doSomething() throws MyException
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