Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple return from try block and finally block both are invoked for one method invocation.

 
Syed Tabrez
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was trying out a simple piece of code to test the exception handling with the following code snippet,

public class ExceptionTest{

public static void main(String ab[]){
System.out.println("test"+method1());
}

static int method1(){
int x= 5;
try{
System.out.println("x:"+x);
//some operation here that might generate an exception
return (x++);
}catch(IllegalArgumentException aee){
throw aee;
}finally{
System.out.println("x:"+x);
return (x++);
}

}
}


I see that the return in try is invoked and also the return from finally is also invoked(x gets incremented twice).
So is it safe to say that the first return(from try) is ignored all the time and the return in finally will always take precedence regardless of any exception ever generated or not ??
If this is so then why isn't the compiler complaining that the return in try block is meaningless ?
Code was tested out on eclipse 3.5.0 java 1.5.
If some one can shed some light on this would be grateful for the help.
 
xsunil kumar
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Syed, if you are using try, catch and finally then always finally will execute except only one senario (system.exit).

If your method has return statement in try and finally both then finally will take effective. As finally will execute after try block. So better not to write return in try / finally except write in after try and finally .

-Sunil
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic