3 ms·
Another option is to fool the compiler. So-called sneaky throws. Something like public static void main(String[] args) { try { sneakyTh
by vbezhenar 8y ago
Another option is to fool the compiler. So-called sneaky throws. Something like
public static void main(String[] args) {
try {
sneakyThrow(new IOException("io"));
Test.<IOException>emulateThrows();
} catch (IOException e) {
e.printStackTrace();
}
}
static void sneakyThrow(Throwable e) {
Test.<RuntimeException>sneakyThrow2(e);
}
private static <E extends Throwable> void sneakyThrow2(Throwable e) throws E {
@SuppressWarnings("unchecked") E e1 = (E) e;
throw e1;
}
static <E extends Exception> void emulateThrows() throws E {
}
- ars 8y agoThis only works if I'm throwing the exceptions myself, but not if I'm using a library function (like a rowMapper for example).
- vbezhenar 8y agoYou can write wrapper which takes function that can throw anything and returns regular java.util.function.Function. Here's example: https://github.com/rainerhahnekamp/sneakythrow/blob/master/src/main/java/com/rainerhahnekamp/sneakythrow/Sneaky.java https://github.com/rainerhahnekamp/sneakythrow/blob/master/s...