javafinally

Strange finally behaviour?


public class Test2 {

    public static void main(String[] args) {
        Test2 obj=new Test2();
        String a=obj.go();

        System.out.print(a);
    }


    public String go() {
        String q="hii";
        try {
            return q;
        }
        finally {
            q="hello";
            System.out.println("finally value of q is "+q);
        }
    }

Why is this printing hii after returning from the function go(), the value has changed to "hello" in the finally block?

the output of the program is

finally value of q is hello
hii

Solution

  • That's because you returned a value that was evaluated from q before you changed the value of q in the finally block. You returned q, which evaluated its value; then you changed q in the finally block, which didn't affect the loaded value; then the return completed, using the evaluated value.

    Don't write tricky code like this. If it confuses the guy who wrote it, imagine the problems it will cause the next guy, a few years down the track when you are somewhere else.