How to use java8 lambda expressions to throw exceptions for custom checks?
•
Java
See English answers > java 8: lambda streams, filter by method with exception 13
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 String (line) method throws checked exceptions, and I call this method from lambda. At this point, you need to throw myexception instead of runtimeException from the readstreamwithjava8 () method
How can I do this with java8?
Solution
The short answer is, you can't This is because foreachordered accepts the consumer and does not declare the consumer Accept throws any exceptions
The solution is to do something similar
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 usually handle exceptions in the process method or use for loops to handle exceptions in the old way
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码