4 ms·
Or in FunctionalInterface, or in anonymous functions. Makes HashMap computeIfAbsent much less useful than it should be. It's impossible to use a function in th
by ars 8y ago
Or in FunctionalInterface, or in anonymous functions.
Makes HashMap computeIfAbsent much less useful than it should be. It's impossible to use a function in there that throws a checked exception (all I want is for the exception to propagate out of computeIfAbsent for the parent method to deal with).
Best option I've found is to wrap it in an unchecked exception, then unwrap it in the parent method, which is just .... yuck.
- vbezhenar 8y agoAnother 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...