Skip to content

Instantly share code, notes, and snippets.

@poetix
Last active November 9, 2015 21:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poetix/e95d562192994ab3f3da to your computer and use it in GitHub Desktop.
Save poetix/e95d562192994ab3f3da to your computer and use it in GitHub Desktop.
A useful Java 8 class for when you want to defer giving a fuck about that checked exception until it's convenient to do so.
@FunctionalInterface
public interface Judiciously<T> {
class WrappedException extends RuntimeException {
public WrappedException(Throwable cause) {
super(cause);
}
}
static <T> T attempt(Judiciously<T> f) {
try {
return f.run();
} catch (RuntimeException | Error e) {
throw e;
} catch (Throwable e) {
throw new WrappedException(e);
}
}
static <T, E extends Throwable> T review(Class<E> exceptionClass, Supplier<T> s) throws E {
try {
return s.get();
} catch (WrappedException e) {
throw (E) e.getCause();
}
}
T run() throws Throwable;
}
public class JudiciouslyTest {
@Test(expected = IOException.class)
public void
wrapsExceptionForLater() throws IOException {
try {
List<String> result = Judiciously.review(IOException.class, () ->
Stream.of("a", "b", "c")
.map(s -> Judiciously.attempt(() -> throwExceptionOnC(s)))
.collect(Collectors.toList()));
} catch (IOException e) {
throw e;
}
}
private String throwExceptionOnC(String s) throws IOException {
if (s.equals("c")) {
throw new IOException();
}
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment