问题:
How can I throw CHECKED exceptions from inside Java 8 streams/lambdas?如何从 Java 8 流/lambda 内部抛出 CHECKED 异常?
In other words, I want to make code like this compile:换句话说,我想让这样的代码编译:
public List<Class> getClasses() throws ClassNotFoundException {
List<Class> classes =
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(className -> Class.forName(className))
.collect(Collectors.toList());
return classes;
}
This code does not compile, since the Class.forName()
method above throws ClassNotFoundException
, which is checked.这段代码不会编译,因为上面的Class.forName()
方法抛出ClassNotFoundException
,它被检查了。
Please note I do NOT want to wrap the checked exception inside a runtime exception and throw the wrapped unchecked exception instead.请注意,我不想将已检查的异常包装在运行时异常中,而是抛出包装的未检查异常。 I want to throw the checked exception itself , and without adding ugly try
/ catches
to the stream.我想抛出已检查的异常本身,并且不向流中添加丑陋的try
/ catches
。
解决方案:
参考一: https://stackoom.com/question/1rzYn参考二: How can I throw CHECKED exceptions from inside Java 8 streams?