aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Clarification on execution of try-catch-finally block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Clarification on execution of try-catch-finally block" Watch "Clarification on execution of try-catch-finally block" New topic
Author

Clarification on execution of try-catch-finally block

Lalit Bansal
Ranch Hand

Joined: Jan 29, 2007
Posts: 63
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

Joined: Feb 15, 2007
Posts: 74
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


SCJP 5 94%<br /><a href="http://amit-wadhwa.blogspot.com/" target="_blank" rel="nofollow">My Blog</a>
 
 
subject: Clarification on execution of try-catch-finally block