0

Here's the code puzzled me:

public Integer getInteger(BlockingQueue<Integer> queue) {
    boolean interrupted = false;
    try {
        while (true) {
            try {
                return queue.take();
            } catch (InterruptedException e) {
                interrupted = true;
                // fall through and retry
            }
        }
    } finally {
        if (interrupted)
            Thread.currentThread().interrupt();
    }
}

It seems like the try block would not stop because of the While(true) block, but I was told that finally block will always be executed after the try block ends. So When will the finally block execute?

user2916610
  • 765
  • 1
  • 5
  • 12

2 Answers2

4

when there's another exception that does not derive from InterruptedException

Valery Gavrilov
  • 184
  • 1
  • 3
4

The finally block will execute when the try block completes, which in your case can be for two reasons:

  • queue.take() completes normally, which means it returns a value, which causes the return statement to complete normally, and return from the method with the value from take().
  • queue.take() completes abruptly by throwing an Exception (or Error) other than InterruptedException.

Abbreviated quote of Java Language Specification "Execution of try-finally and try-catch-finally":

  • If execution of the try block completes normally, then the finally block is executed [...]

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

    • If the run-time type of V is assignment compatible with a catchable exception class of any catch clause [...] Then there is a choice:

      • If the catch block completes normally, then the finally block is executed [...]

      • If the catch block completes abruptly for reason R, then the finally block is executed [...]

    • If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the finally block is executed [...]

  • If execution of the try block completes abruptly for any other reason R, then the finally block is executed [...]

All paths lead to "finally block is executed".

In short, the finally block is always executed when the try block completes, for whatever reason. The only way for that not to happen, is an abnormal termination of the JVM (e.g. JVM kill, JVM crash, OS crash, or power loss).

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247