java - 为什么我无法捕获此 FileNotFoundException?

标签 java eclipse debugging exception io

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。但是,当我 try catch 文件的 FileNotFoundException 时,Eclipse 说这是无法访问的代码?基本上这个位在这里:

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

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

最佳答案

文件的构造函数不会抛出 FileNotFoundException,您可以在 Javadoc 处看到它。 :

public File(String pathname)

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

Parameters: pathname - A pathname string

Throws:NullPointerException - If the pathname argument is null

但是 FileReader 抛出异常!再次,另一个javadoc

public FileReader(File file) throws FileNotFoundException Creates a new FileReader, given the File to read from.

Parameters: file - the File to read from

Throws: FileNotFoundException - if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

关于java - 为什么我无法捕获此 FileNotFoundException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41021120/

相关文章:

java - XML 编码器还是二进制编码器? - Eclipse Milo(客户端-服务器)

java - 参数 [frmStartupGame] 的修饰符非法;只允许最终的

android - Chrome 检查设备不显示 android 应用程序

c - 我如何跟踪内存分配?

java - 异常 java.sql.SQLException : Parameter index out of range (1 > number of parameters, 为 0)

java - 无法加载标签 "org.apache.struts2.views.jsp.ui.FormTag"的标签处理程序类 "s:form"

java - 在 joda 中覆盖一周的第一天?

java - Camel CXF : IllegalArgumentException parameters should be of type X

eclipse - 将 Eclipse 命令绑定(bind)/绑定(bind)到 swt 按钮

c# - 获取对象的完整字符串表示形式(如在 Visual Studio 的即时窗口中)