Skip to content

Instantly share code, notes, and snippets.

@takawitter
Created October 19, 2016 04:20
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 takawitter/004bfa4b4876e43a8a7c766f44d987e7 to your computer and use it in GitHub Desktop.
Save takawitter/004bfa4b4876e43a8a7c766f44d987e7 to your computer and use it in GitHub Desktop.
Using Iterable.forEach by tunneling exception that may occur inside Consumer.
public class Test{
@Test
public void test_tunnelingExecute() throws Throwable{
try{
tunnelingExecute(
Arrays.asList(1, 2, 3)::forEach,
v -> {throw new IOException();}
);
Assert.fail();
} catch(IOException e){
}
}
public static interface ConsumerWithException<T, E extends Throwable>{
void accept(T value) throws E;
}
@SuppressWarnings("serial")
public static class SoftenedException extends RuntimeException {
public SoftenedException(Throwable cause) {
super(cause);
}
}
@SuppressWarnings("unchecked")
public static <P, E extends Throwable> void tunnelingExecute(
Consumer<Consumer<P>> term, ConsumerWithException<P, E> proc)
throws E{
try{
term.accept(pr -> {
try{
proc.accept(pr);
} catch(Error | RuntimeException e){
throw e;
} catch(Throwable e){
throw new SoftenedException(e);
}
});
} catch(SoftenedException e){
throw (E)e.getCause();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment