【问题标题】:Java unreachable catch block for FileNotFoundExceptionFileNotFoundException 的 Java 无法访问的 catch 块
【发布时间】:2018-06-29 13:09:05
【问题描述】:

我目前对为什么收到“FileNotFoundException 的无法访问的 catch 块”感到困惑。当我尝试运行我的代码时。我从主方法参数中获取文件路径,并在输入路径错误或在路径中找不到文件的实例中捕获错误。

有人可以帮我解决这个问题吗?这是我这部分的代码:

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");
    }

【问题讨论】:

  • 构造函数 File(String) 不会抛出 FileNotFoundException
  • 文件对象只是对可能存在或不存在的文件或目录路径的引用,这就是File 类型具有exists() 方法的原因。

标签: java exception-handling try-catch filenotfoundexception


【解决方案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 是有道理的。试试看。

【讨论】:

  • 我很困惑,因为当我故意弄乱路径时,它给了我 FileNotFoundException,而当我调试它时,它是在新的 File() 创建上。
  • 据我所知,仅此行 new File(inputFilePath) 是不可能的。你能给我一个重现问题的例子吗?
  • 我认为它实际上可能是文件声明行下的扫描仪。我查看了 api,看起来 Scanner 抛出了 FileNotFoundException。我刚刚了解了 File exists() 方法,所以我应该改用它
猜你喜欢
  • 2015-05-11
  • 1970-01-01
  • 2014-10-26
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多