Java 为什么我不能捕获此FileNotFoundException?
send方法返回空的BufferedReader,因为找不到该文件。Eclipse只是说,由于print方法,存在一个NullPointerException,但是当我删除所有try/catch语句时,Eclipse说我需要编写该方法引发IOException或FileNotFoundException,它还允许我这样做,如果我不这样做,它就会引发FileNotFoundException。然而,当我试图捕获该文件的FileNotFoundException时,Eclipse说这是无法访问的代码?基本上这一点:Java 为什么我不能捕获此FileNotFoundException?,java,eclipse,debugging,exception,io,Java,Eclipse,Debugging,Exception,Io,send方法返回空的BufferedReader,因为找不到该文件。Eclipse只是说,由于print方法,存在一个NullPointerException,但是当我删除所有try/catch语句时,Eclipse说我需要编写该方法引发IOException或FileNotFoundException,它还允许我这样做,如果我不这样做,它就会引发FileNotFoundException。然而,当我试图捕获该文件的FileNotFoundException时,Eclipse说这是无法访问的代码
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;
}
}
当删除try/catch语句允许我抛出FileNotFoundException时,为什么Eclipse会说此代码不可访问?文件的构造函数不会抛出FileNotFoundException,您可以在以下位置看到它:
try {
file = new File(filename);
} catch(FileNotFoundException e) {
System.err.println("Could not find file!");
}
公共文件(字符串路径名)
通过转换创建新的文件实例
将给定的路径名字符串转换为抽象路径名。如果给定
字符串是空字符串,则结果是空摘要
路径名
参数:路径名-路径名字符串
抛出:NullPointerException-如果pathname参数为null
但是文件阅读器抛出!再一次,另一个
公共文件读取器(文件)
抛出FileNotFoundException根据要读取的文件创建新的文件读取器
参数:file-要从中读取的文件
抛出:FileNotFoundException-如果文件不存在,则为
目录而不是常规文件,或者由于其他原因无法
开放阅读
文件的构造函数不会抛出FileNotFoundException,您可以在以下位置看到它: 公共文件(字符串路径名) 通过转换创建新的文件实例 将给定的路径名字符串转换为抽象路径名。如果给定 字符串是空字符串,则结果是空摘要 路径名 参数:路径名-路径名字符串 抛出:NullPointerException-如果pathname参数为null 但是文件阅读器抛出!再一次,另一个 公共文件读取器(文件) 抛出FileNotFoundException根据要读取的文件创建新的文件读取器 参数:file-要从中读取的文件 抛出:FileNotFoundException-如果文件不存在,则为 目录而不是常规文件,或者由于其他原因无法 开放阅读 构造函数
文件(filename)
不会抛出FileNotFoundException
,即使该文件不存在,也可以使用File.exists()
检查是否存在
如果尝试读取不存在的文件,将引发FileNotFoundException。构造函数文件(filename)
不会引发FileNotFoundException
,即使文件不存在,也可以使用file.exists()
检查是否存在
如果您尝试读取不存在的文件,将引发FileNotFoundException。我刚刚尝试运行您的程序。下面的图片显示该文件不是空的
文件
是通过文件路径
为空创建的。如果要捕获文件不存在时的FileNotFoundException
,可以执行以下操作:
try {
file = new File(filename);
} catch(Exception e) {
System.err.println("Could not find file!");
}
我只是试着运行你的程序。下面的图片显示该文件不是空的
文件
是通过文件路径
为空创建的。如果要捕获文件不存在时的FileNotFoundException
,可以执行以下操作:
try {
file = new File(filename);
} catch(Exception e) {
System.err.println("Could not find file!");
}
新文件(文件名)
不会引发FileNotFoundException
,您可以创建没有现有物理文件的文件
对象(这就是方法存在()
,存在的原因)。新文件(文件名)
不会引发FileNotFoundException
,允许您在没有现有物理文件的情况下创建File
对象(这就是为什么方法exists()
,exists)。