• Post Reply Bookmark Topic Watch Topic
  • New Topic

try/finally block  RSS feed

 
anish jain
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public int f(){
int i=9;
try{
i=99;
return i;
}finally{
i=10;
}
}

When i call the above method, it returns 99.
I didn't understand the logic behind this. I thought the method will return 10, rather it returned 99.
can anybody please explain me the logic behind it?
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You only set i to 10 after you return 99. If you use return i in the finally block, it will return 10 instead of 99.

Please UseCodeTags when you post code, Anish.
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you will not even reach the finally block as there is a return statement before it..

if you want to return 10 then say

 
anish jain
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shanky finally block will be executed irrespective of a return statement in try
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
anish jain wrote:Shanky finally block will be executed irrespective of a return statement in try



Oops yes you are right
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!