This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
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: 133
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
 
 
subject: Simple return from try block and finally block both are invoked for one method invocation.
 
Similar Threads
Un reachable statement (Sorry for posting the same topic second time...)
Un reachable statement
exception trouble
Reg. unreachable code
finally question