Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exceptions to control flow - code smell? [closed]

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?

like image 362
Yuval Adam Avatar asked Jan 21 '09 16:01

Yuval Adam


People also ask

Can exception handling be used for flow control?

If you use exceptions for the control flow, it may cause performance issues and your code may be less readable. Hope this helps!

How do you handle exceptions in flow?

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.

How do you use exceptions correctly?

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.


1 Answers

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
like image 97
Michael Borgwardt Avatar answered Oct 08 '22 21:10

Michael Borgwardt