【发布时间】: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