This is what I'm trying to do:
try {
//code
} catch (Exception e) {
return false;
} finally {
//close resources
}
Will this work? Is it bad practice? Would it be better doing this:
boolean inserted = true;
try {
//code
} catch (Exception e) {
inserted = false;
} finally {
//close resources
}
return inserted;
Yes, it will. The only things that can prevent a finally block to execute (AFAIR) are System.exit()
, and an infinite loop (and a JVM crash, of course).
The finally
block is executed always, unconditionally, as the last thing the try-catch-finally
block does. Even if you execute Thread#stop
against it, the finally
block will still execute, just as if a regular exception ocurred.
Not just that, if you return from finally
, that return value will trample over the return from either try
or catch
.
BTW Your first example is not just fine, but preferred. In the second example the reader must chase around the assignments to the variable, which is a tedious job and lets bugs slip through very easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With