Tuesday 10 July 2007

try surprise me, catch my surprise, finally I'm surprised


public static int doSomething() {
int i = 0;
try {
i = 1;
System.out.print("a");
return i;
}
catch (Exception e) {
i = 2;
System.out.print("b");
return i;
}
finally {
i = 3;
System.out.print("c");
return i;
}
} // end

return ?

return 3 ! and print "ac".

This code behave like the finally block is an inside method:

public static int doSomething() {
int i = 0;
try {
i = 1;
System.out.print("a");
{ // finally block
int another_i = 3;
System.out.print("c");
return another_i;
}
return i;
}
catch (Exception e) {
i = 2;
System.out.print("b");
{ // finally block
int another_i = 3;
System.out.print("c");
return another_i;
}
return i;
}
} // end

...
So, and if there is no return in finally block.

public static int doSomething() {
int i = 0;
try {
i = 1;
System.out.print("a");
return i;
}
catch (Exception e) {
i = 2;
System.out.print("b");
return i;
}
finally {
i = 3;
System.out.print("c");
// return i;
}
} // end

It return 1 and print "ac".
Behave like that:

public static int doSomething() {
int i = 0;
try {
i = 1;
System.out.print("a");
{ // finally block
int another_i = 3;
System.out.print("c");
}
return i;
}
catch (Exception e) {
i = 2;
System.out.print("b");
{ // finally block
int another_i = 3;
System.out.print("c");
}
return i;
}
} // end


The try-catch-finally doesn't really behave as first expected.
See Java Hall Of Shame
and finally.

No comments: