nick woodward wrote:The only example i could think of is to allow you to mix and match the benefits of ducking an exception and running code in the finally block. Does that sound about right?
That sounds about right, although there are other examples as well
Probably an obvious is described in the following code snippet (prior to
Java 7)
If something went wrong while reading the file to create the list of lines in the
readLines method, you don't want to process the lines because that's pretty useless. So the IOException is thrown from the
readLines method and handled in the
calculate method. But you definitely want to close all resources you have used. When using
try-with-resources (Java 7 and later) the
readLines method is more concise but the code is equivalent (the compiler will generate the appropriate
finally block for you)
Another example is when you are working with concurrency and locks. When you acquire a lock, you always want to release this lock once you are done. So all code that needs to be executed while the lock is held, will be executed inside a try-finally block and releasing the lock happens in the finally block. This way you are ensured the lock is always released when necessary
This idiom is even documented in the
API documentation.
Hope it helps!
Kind regards,
Roel
Disclaimer: none of these topics (
try-with-resources, file I/O, concurrency, and locks) are
not a topic of the OCA certification exams. I used them for demonstration purposes only. So if you don't understand what's happening, don't worry and just move on! All these topics are an OCP exam objective.
[edit] Forgot to mention that
try-with-resources and file I/O are also not on the OCA exam. Thanks Jeanne!