0

I have a method, it hints that the return statement is missing, but I don’t think the statement return -1 will be executed. Can anybody tell me why?

private int loop() {
    int retryTimes = 2;
    do {
        try {
            // simulate real business
            int value = new Random().nextInt(3);
            if (value % 3 != 0) {
                throw new RuntimeException();
            }
            return value;
        } catch (Exception e) {
            if (retryTimes <= 0) {
                throw e;
            }
        }
    } while (retryTimes-- > 0);
    // if below line not exists; prompt error: missing return statement
    return -1;
}
1
  • It's just because the compiler is not able to detect that it will never reach this line Commented Dec 11, 2020 at 5:42

2 Answers 2

1

The Java compiler suspects that should the while loop iterate more than 2 times, that line with the return -1 would be reached. And, should there not a be a return statement there, then it would be a problem.

That your actual code's logic doesn't necessarily allow for this doesn't matter to the compiler. There can always be unexpected exceptions, so you should rightfully have a catch-all return statement at the end of the method, outside the loop.

Sign up to request clarification or add additional context in comments.

Comments

0

You can put the return statement inside the catch block like this since you are returning a value on the successful execution, you also need to return a value on failure.

     private int loop() {
        int retryTimes = 2;
        do {
            try {
                // simulate real business
                int value = new Random().nextInt(3);
                if (value % 3 != 0) {
                    throw new RuntimeException();
                }
                return value;
            } catch (Exception e) {
                if (retryTimes <= 0) {
                    throw e;
                }
                return -1;
            }
        } while (retryTimes-- > 0);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.