gpt4 book ai didi

java - lambda 不需要异常处理

转载 作者:行者123 更新时间:2023-12-01 16:43:16 25 4
gpt4 key购买 nike

想象一下有这个方法:

public static File[] listDirectoryFiles(File directory) throws IllegalArgumentException {
if (!directory.isDirectory())
throw new IllegalArgumentException("Enter a directory");
return directory.listFiles(File::isDirectory);
}

然后这样调用它:

File myDir = new File("C:\\Users\\bobby\\Downloads");
Arrays.asList(listDirectoryFiles(myDir)).forEach(System.out::println);

既然签名包含抛出IllegalArgumentException,为什么不需要实际try-catchlistDirectoryFiles的调用?

最佳答案

IllegalArgumentExceptionRuntimeException 的子类:

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

关于java - lambda 不需要异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58506275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com