D
Daniel Pitts
Roger said:pek said:I can completely remove the finally block in your example and the code
works exactly the same. I also think that I can completely remove the
finally as a general rule in which case I have the drawbacks I mention
previously: duplication of code and returning outside a try/catch.
Simple example with finally:
public class Thrower {
public static void main(String[] args) {
new Thrower().callit();
System.err.println("I better NOT be printed");
}
private void callit() {
try {
doA();
} finally {
doB();
}
}
private void doB() {
System.err.println("I better be printed");
}
private void doA() {
throw new RuntimeException("Did not expect me, did you?");
}
}
To get the same behaviour without finally I'd need soething like:
public class Thrower2 {
public static void main(String[] args) {
new Thrower2().callit();
System.err.println("I better NOT be printed");
}
private void callit() {
try {
doA();
} catch (Throwable t) {
doB();
T.local.set(t);
try {
T.class.newInstance();
} catch (InstantiationException e) { // Should not happen
} catch (IllegalAccessException e) { // Should not happen
}
}
}
private void doB() {
System.err.println("I better be printed");
}
private void doA() {
throw new RuntimeException("Did not expect me, did you?");
}
private static class T {
static ThreadLocal<Throwable> local = new ThreadLocal<Throwable>();
public T() throws Throwable {
throw local.get();
}
}
}
And even then I have introduced the chance that T is not available (see
the two exception I have chosen to ignore).
If you're going to be doing that sort of trickery:
sun.misc.Unsafe.getUnsafe().throwException(t);