【问题标题】:Why can I not catch this FileNotFoundException?为什么我无法捕捉到这个 FileNotFoundException?
【发布时间】:2017-04-22 14:42:00
【问题描述】:
package test4;

import java.io.*;

public class Reader {

    public static void main(String[] args) {
        print(send("test.txt"));
    }

    public static BufferedReader send(String filename) {
        File file = null;
        FileReader filer = null;
        BufferedReader filed = null;

        try {
            file = new File(filename);
        } catch(FileNotFoundException e) {
            System.err.println("Could not find file!");
        }

        try {
            filer = new FileReader(file);
        } catch(Exception e) {
            System.err.println("Could not initialize file reader!");
        }

        try {
            filed = new BufferedReader(filer);
        } catch(Exception e) {
            System.err.println("Could not initialize buffered reader!");
        }

        return filed;
    }
}

send 方法返回 null BufferedReader,因为找不到文件。 Eclipse 只是说由于 print 方法存在 NullPointerException,但是当我删除所有 try/catch 语句时,Eclipse 说我需要编写该方法抛出 IOException 或 FileNotFoundException,它也允许我这样做,如果我不要然后它抛出一个 FileNotFoundException。但是,当我尝试为文件捕获 FileNotFoundException 时,Eclipse 说这是无法访问的代码?基本上这点在这里:

    try {
        file = new File(filename);
    } catch(FileNotFoundException e) {
        System.err.println("Could not find file!");
    }

当仅删除 try / catch 语句允许我抛出 FileNotFoundException 时,为什么 Eclipse 会说这段代码无法访问?

【问题讨论】:

  • new File(filename) 不会抛出FileNotFoundException,您可以在没有现有物理文件的情况下创建File 对象(这就是exists() 方法存在的原因)。

标签: java eclipse debugging exception io


【解决方案1】:

文件的构造器不会抛出 FileNotFoundException,你可以在这里看到它,Javadoc

公共文件(字符串路径名)

通过转换创建一个新的 File 实例 将给定的路径名​​字符串转换为抽象路径名。如果给定 string 为空字符串,则结果为空摘要 路径名。

参数:pathname - 一个路径名字符串

Throws:NullPointerException - 如果路径名参数为空

但是 FileReader 抛出了!又是一个javadoc

public FileReader(文件文件) throws FileNotFoundException 创建一个新的 FileReader,给定要读取的文件。

参数:file - 要读取的文件

抛出:FileNotFoundException - 如果文件不存在,则为 目录而不是常规文件,或者由于某些其他原因不能 开放阅读。

【讨论】:

    【解决方案2】:
    try {
        file = new File(filename);
    } catch(Exception e) {
        System.err.println("Could not find file!");
    }
    

    【讨论】:

      【解决方案3】:

      构造函数File(filename)不会抛出FileNotFoundException,即使文件不存在,也可以使用file.exists()进行检查。

      如果您尝试读取不存在的文件,将引发 FileNotFoundException。

      【讨论】:

        【解决方案4】:

        我刚刚尝试运行您的程序。下面的图片说文件不为空

        file 是在 filePath 为空时创建的。如果你想在文件不存在的情况下捕获FileNotFoundException,你可以这样做:

                if(!file.exists()){
                    throw new FileNotFoundException("File not found");
                }
        

        【讨论】:

          猜你喜欢
          • 2021-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多