I have some code (with some more nested forEach's
and streams
):
void process() throws RuntimeException
{
try {
ArrayList<Integer> ints = new ArrayList<>();
ints.add(1);
ints.add(2);
ints.add(3);
ints.forEach(e -> {
System.out.println(e);
throw new RuntimeException("RuntimeException");
});
}
catch (RuntimeException rex)
{
rex.printStackTrace();
throw rex; // throw it up, and up, and up...
}
}
It does not work because foreach's
Consumer's
accept()
doesn't throw an exception by default. Even if it would have a throws
signature - I couldn't catch it outside of the block.
What I need to do is to catch the exception from the foreach()
method itself.
Is there any way I could achieve that without some external methods like
void handleException(RuntimeException ex){ ... }
and calling it in every forEach()'s
try/catch ?