Last active
November 9, 2015 21:48
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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