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/