FileNotFoundException的Java无法访问的catch块

时间:2018-06-29 13:09:06

标签: java exception-handling try-catch filenotfoundexception

我现在对为什么收到“ FileNotFoundException的无法到达的捕获块”感到困惑。当我尝试运行我的代码时。我正在从主要方法参数中获取文件路径,并在输入路径错误或路径中找不到文件的情况下捕获错误。

有人可以帮我吗?这是我这部分的代码:

public void readFile(String inputFilePath, String outputFilePath) throws IOException{

    StringBuilder sb = new StringBuilder();

    File input = null;

    try{
    input = new File(inputFilePath);
    }
    catch (FileNotFoundException e){
        System.err.println("Input file cannot be found in the provided path");
    }

1 个答案:

答案 0 :(得分:2)

因为这行

input = new File(inputFilePath);

不会引发FileNotFoundException

如果您深入研究new File(..)的代码

public File(String pathname) {
     if (pathname == null) {
         throw new NullPointerException();
     }
     this.path = fs.normalize(pathname);
     this.prefixLength = fs.prefixLength(this.path);
}

如您所见,此方法不会抛出FileNotFoundException,只有NPE的可能性。

如果要扩展代码以读取这样的文件

new BufferedInputStream(new FileInputStream(input));  

然后FileNotFoundException才有意义。试试吧。