有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

异常处理FileNotFoundException的Java不可访问捕获块

我现在很困惑,为什么我会收到“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) 个答案

  1. # 1 楼答案

    因为这条线

    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就有意义了。试试看