Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Clarification on execution of try-catch-finally block

 
Lalit Bansal
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The SCJP5 book from Kathy Sierra/Bert Bates states the following (under Chapter 5, Handling Exceptions topic):
A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered, and before the return executes!

I tested the above statement with following example:

public class TestClass {

/**
* @param args
*/
public static void main(String[] args) {

justAMethod();
}

public static String justAMethod() {
try{
System.out.println("inside try--before exception");
//int i = 3/0;
System.out.println("inside try--after exception");
return justAnotherMethod();

}
catch(Exception e){
System.out.println("inside catch");
}
finally {
System.out.println("inside finally");

}
return justAnotherMethod();

}
public static String justAnotherMethod() {
System.out.println("Hello World");
return null;
}

}


and the output was:

inside try--before exception
inside try--after exception
Hello World
inside finally


Even though the book says "finally block executes right after the return statement is encountered, and before the return executes!", the ouput of above code doesn't match the book statement. In other words, the return statement in above code is executing first and then the finally block is being called.

Kindly clarify.
 
Amit Wadhwaa
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lalit,

In here, the method is not executing the return statement,
-->return methodcall()
In this it first evaluates the expr. (method call) and then goes to finally and then returns

To confirm instead of return method(), try return "someString" and print that value from the calling method.

Just to ponder, if it didn't do that, what wd have happenned if in "return methodcall()" methodcall() threw an exception and had a throws clause.

Best of luck, I will also be giving the exam in a week or so
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic