Forums Register Login

Try an Finally Working Confusion

+Pie Number of slices to send: Send
If i write a return statement inside try block
and that try block also has a finally block then will the finally block execute
eg: try{
return 0;
}
catch(Exception e)
{

}
finally{
System.out.println("Final Block");
} .?
2
+Pie Number of slices to send: Send
Try it out, see what happens. That's by far the best approach when you've got a question like that.
1
+Pie Number of slices to send: Send
The runtime system always executes the statements within the finally block regardless of what happens within the try block.
+Pie Number of slices to send: Send
The finally bock code is always executed, irrespective of anything happening inside the try block. That is the sole purpose of finally block in java.
1
+Pie Number of slices to send: Send
And once you've observed what happens, learn this rule: Never return, throw, break, or continue out of a finally block. Since finally is just for cleanup, we don't want it to change how its try statement completes.
+Pie Number of slices to send: Send
I agree. If you need to return / throw / break etc if the try block succeeded or not, just put it after the try-catch(-finally) block.
+Pie Number of slices to send: Send
 

Rob Spoor wrote:I agree. If you need to return / throw / break etc if the try block succeeded or not, just put it after the try-catch(-finally) block.



Or inside the try.

Never mind. Mis-read.
+Pie Number of slices to send: Send
I think you missed the "or not". What I meant was returning the same value from the try and catch blocks without duplicating that code.
So instead of
use
+Pie Number of slices to send: Send
 

Rob Spoor wrote:I think you missed the "or not".



Yup.
Who among you feels worthy enough to be my best friend? Test 1 is to read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1436 times.
Similar Threads
Statement not reachable??
try/finally block
Doubt in try finally .......
Finally block
return of the try-catch
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 03:12:31.