Showing posts with label catch. Show all posts
Showing posts with label catch. Show all posts

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.

Tuesday 26 June 2007

SolarFlaresException


try {
doSomethingInSpace();
}
catch (SolarFlaresException e) {
LOG.warn("Watch the solar winds !" + e);
}


This is just a joke from an article about programming for spacecraft.

Three Minutes With Mike Deliman

A Conversation with Mike Deliman