“Finally” get understood

I have been always use finally to clean up the mess to make my method end up gracefully, and it looks like the the finally code block is the last stop of the code flow. But wait, have you ever think about why IDE are not force you to write a return statement? If it is really the last stop, then you need to add return statement for a method requires a output parameter. It looks weird, but fortunately I could look for answer in my Eclipse:

public int f1(){
try{
x = 1;
return x;
}finally{
x = 2;
}
}

And this method print 1. So it looks the finally is NOT the last stop, otherwise we should saw 2. What’s wrong? Then I expended the method a bit:

public class TestTryCatchFinally {
static int x = 0;

public static void main(String[] args){
System.out.println(f1() );
System.out.println(f2() );
}

public static int f1(){
try{
x = 1;
return x;
}finally{
x = 2;
}
}

public static int f2(){
return x;
}
}

We got

1

2

printed this time, it proof the finally block is really the last one get executed, even after return statement.

Advertisements