Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will finally clause always always execute?

Tags:

java

try {
    if (myBoolean) {
        while (true) ;
    } else {
        System.exit(1);
    }
} finally {
    code.to.cleanup();
}

I am not entirely sure, but here's the above code snippet that i feel may cause the finally clause to not execute, regardless of myBoolean's value

like image 966
bouncingHippo Avatar asked Feb 11 '26 13:02

bouncingHippo


1 Answers

No, 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.

(As Peter points out however, while(true) ; will obviously block indefinitely. A just assumed that the while (true) ; was a stub for something that made more sense :)

like image 171
aioobe Avatar answered Feb 13 '26 10:02

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!