Lambda不需要异常处理

pay*_*yne 0 java lambda exception

想象一下这种方法:

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

然后以这种方式调用它:

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

由于签名包括在内throws IllegalArgumentException,为什么实际上不需要try-catch致电listDirectoryFiles

孙兴斌*_*孙兴斌 5

IllegalArgumentException是的子类RuntimeException

RuntimeException及其子类是未经检查的异常。如果未检查的异常可以由方法或构造函数的执行引发,并且可以在方法或构造函数的边界外传播,则无需在方法或构造函数的throws子句中声明未检查的异常。