wood burning stoves 2.0*
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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

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) {


public static String justAMethod() {
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>
I agree. Here's the link: http://aspose.com/file-tools
subject: Clarification on execution of try-catch-finally block
Similar Threads
return statement in a try block
code following the finally block.
Exception:Unexpected output
try, catch,finally
Unreachable statement