6
try {
    if (check) {
        while (true) ;
    } else {
        System.exit(1);
    }
} finally {
    clear();
}

Q: Is there a case where clear() never gets executed? I personally feel that there are no cases where clear() will not be executed.

LaneLane
  • 345
  • 7
  • 16

5 Answers5

4

If System.exit succeeds, the clear() will not be executed. However, System.exit(1) could throw SecurityException exception, in which case clear() will be executed.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

If check is true, then you are stuck in an infinite loop, in which case you never technically get to the finally block.

Else if check is false, then System.exit(1); is executed and your program terminates; in which case it never gets to the finally block to execute clear().

In this example, it is actually not possible to reach clear()

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
0

clear will only be executed when the try block completes.

If check is true then the while(true) will sit there forever so never leave the try block

If check is false the System.exit(0) will just exit the program so the finally block will not run then either. But System.exit(int) can throw a SecurityException which would then cause the finally to be called.

So in summary I think it can be called if System.exit throws a SecurityException

RNJ
  • 15,272
  • 18
  • 86
  • 131
0

Is there a case where clear() never gets executed?

The two examples you have given, this is the case as you can confirm by running the code.

When you have an infinite loop, nothing is executed after it.

When System.exit() is successful, it stops the thread immediately.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
-1

System.exit(1) prevents the finally clause from running.

Basically a finally block is executed after a try/catch regardless if the try or the catch returned normally or exceptionally.

A System.exit however prevents the block from returning at all.

while(true) ; will obviously block indefinitely. just assumed that the while (true) ; was a stub for something that made more sense :)

bouncingHippo
  • 5,940
  • 21
  • 67
  • 107