public class MyCheckedException extends Exception{
@java.io.Serial
private static final long serialVersionUID = -1574710658998033284L;
public MyCheckedException() {
super();
}
public MyCheckedException(String s) {
super(s);
}
}
public class MyStudents {
public int changeAgeWithCheckedException() throws MyCheckedException {
throw new MyCheckedException();
}
public int changeAgeWithUnCheckedException(){
throw new RuntimeException();
}
}
好了,我们首先在lambda表达式中抛出CheckedException:
public static void streamWithCheckedException(){
Stream.of(new MyStudents()).map(s->s.changeAgeWithCheckedException()).toList();
}
public static <T extends Exception,R> R sneakyThrow(Exception t) throws T {
throw (T) t;
}
这个方法接收一个checked exception,在内部强制转换之后,抛出T。
看看在代码中如何使用:
public static void sneakyThrow(){
Stream.of(new MyStudents()).map(s -> SneakilyThrowException.sneakyThrow(new IOException())).toList();
}
代码可以编译通过,这说明我们已经把checked异常转换成为unchecked异常了。
运行之后你可以得到下面的输出:
Exception in thread "main" java.io.IOException
at com.flydean.Main.lambda$sneakyThrow$1(Main.java:28)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at java.base/java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:411)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:575)
at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:616)
at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:622)
at java.base/java.util.stream.ReferencePipeline.toList(ReferencePipeline.java:627)
at com.flydean.Main.sneakyThrow(Main.java:28)
at com.flydean.Main.main(Main.java:9)