I have the code below.
private static void readStreamWithjava8() {
Stream<String> lines = null;
try {
lines = Files.lines(Paths.get("b.txt"), StandardCharsets.UTF_8);
lines.forEachOrdered(line -> process(line));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (lines != null) {
lines.close();
}
}
}
private static void process(String line) throws MyException {
// Some process here throws the MyException
}
Here my process(String line)
method throws the checked exception and I'm calling that method from within the lambda. At that point need to throw the MyException
from readStreamWithjava8()
method without throwing RuntimeException
.
How can I do this with java8?
The short answer is that you can't. This is because forEachOrdered
takes a Consumer
, and Consumer.accept
is not declared to throw any exceptions.
The workaround is to do something like
List<MyException> caughtExceptions = new ArrayList<>();
lines.forEachOrdered(line -> {
try {
process(line);
} catch (MyException e) {
caughtExceptions.add(e);
}
});
if (caughtExceptions.size() > 0) {
throw caughtExceptions.get(0);
}
However, in these cases I typically handle the exception inside the process
method, or do it the old-school way with for-loops.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With