Using a try-catch-finally construction to retrieve a database record, it seems that I need to return a value inside a try
block in case everything was fine (as in case of an exception the end of the function is not meant to be reached). But If I return inside try
, is finally
code going to be reached (to close the connection etc.)?
Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.
Yes, we can write a return statement of the method in catch and finally block.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
In a try-catch-finally block that has return statements, only the value from the finally block will be returned. When returning reference types, be aware of any updates being done on them in the finally block that could end up in unwanted results.
Yes,
The result of the try/catch
expression will be the last line of either the try
or catch
block, but the finally
block will always execute no matter what
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