In Java docs I'm reading this: The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
When would you ever exit a try block with a break or continue ? The only scenarios I can think of is you are running a loop inside of a try block and you exit using a break/continue but that should just exit outside of a loop and not the try block itself right?
When would you ever exit a try block with a break or continue?
When you have a try inside a loop; e.g.
for (Cat cat : cattery) {
try {
cat.removeFromCage();
cat.healthCheck();
if (cat.isPedigree()) {
continue;
}
cat.spey();
} finally {
cat.putBackInCage();
}
}
OK ... so there are more elegant ways of writing that "code" ... but it is just an illustration.
The only scenarios I can think of is you are running a loop inside of a try block and you exit using a break/continue but that should just exit outside of a loop and not the try block itself right?
That is right.
FWIW, any piece of code that involves breaking out of a try block or returning from a catch or finally or any of the other "edge case" things should probably be simplified. The JLS specifies clearly what happens in these scenarios ... but that doesn't mean you should use them in a real program.
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