Skip to content

Instantly share code, notes, and snippets.

@melix
Created May 7, 2015 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melix/1636ac330fafdb39bdb8 to your computer and use it in GitHub Desktop.
Save melix/1636ac330fafdb39bdb8 to your computer and use it in GitHub Desktop.
Dirty exception rethrow
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class Beurk {
private final static Unsafe UNSAFE;
static {
Unsafe unsafe = null;
try {
Field unsafeField = null;
unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = (Unsafe) unsafeField.get(null);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
e.printStackTrace();
}
UNSAFE = unsafe;
}
public static interface Factory<T> {
T create();
}
public static <T> T wrappingCall(Factory<T> factory) {
long sd = System.currentTimeMillis();
T result = null;
Throwable error = null;
try {
result = factory.create();
} catch (Throwable e) {
error = e;
}
long ed = System.currentTimeMillis();
if (error == null) {
System.out.printf("Success: %dms%n", ed - sd);
} else {
System.err.printf("Failure !%s:%dms%n", error.getMessage(), ed - sd);
// how do you rethrow e, so that the wrapping call is "passive"?
// Groovy has an utility class for this
// in Java, you can do this but not a public API:
UNSAFE.throwException(error);
}
return result;
}
public static void main(String... args) {
String good = wrappingCall(() -> {
return "good";
});
System.out.println("good = " + good);
String evil = wrappingCall(() -> {
StringBuilder sb = new StringBuilder("Ahahahaha");
while (sb.length() < Integer.MAX_VALUE) {
sb.append(sb.toString());
}
return sb.toString();
});
System.out.println("evil = " + evil);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment