Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Try an Finally Working Confusion

 
Deepak PatilPune
Greenhorn
Posts: 1
Firefox Browser MyEclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
} .?
 
Matthew Brown
Bartender
Posts: 4566
8
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try it out, see what happens. That's by far the best approach when you've got a question like that.
 
Zeeshan Sheikh
Ranch Hand
Posts: 144
Java MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The runtime system always executes the statements within the finally block regardless of what happens within the try block.
 
Dinesh Sing
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:I think you missed the "or not".


Yup.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic