Created
October 19, 2016 04:20
-
-
Save takawitter/004bfa4b4876e43a8a7c766f44d987e7 to your computer and use it in GitHub Desktop.
Using Iterable.forEach by tunneling exception that may occur inside Consumer.
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 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