aspose file tools
The moose likes Beginning Java and the fly likes Simple return from try block and finally block both are invoked for one method invocation. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Simple return from try block and finally block both are invoked for one method invocation. " Watch "Simple return from try block and finally block both are invoked for one method invocation. " New topic
Author

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

Syed Tabrez
Greenhorn

Joined: Dec 22, 2009
Posts: 9
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

Joined: Dec 14, 2009
Posts: 125
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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Simple return from try block and finally block both are invoked for one method invocation.
 
Similar Threads
Reg. unreachable code
exception trouble
Un reachable statement
finally question
Un reachable statement (Sorry for posting the same topic second time...)