When is finally justified?

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);
 
R

Roger Lindsjö

Daniel said:
If you're going to be doing that sort of trickery:

sun.misc.Unsafe.getUnsafe().throwException(t);

Oh, didn't know about that. But I will (as I am sure you will too)
continue to use the try...finally construct instead.
 
B

blue indigo

Roger Lindsjö wrote: [lots of code]
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);

Eh -- isn't using sun.*, well ... unsafe?

ThreadLocal is a hack, but it won't change out from under you in future
JDK versions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top