【发布时间】:2016-07-17 05:15:19
【问题描述】:
我有两个文本文件,如果找不到文件,我想抛出异常。我有一个 FileReader 类来检查文件是否存在,并且在我的主目录中我尝试捕获异常。
public FileReader() throws FileNotFoundException {
super();
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
//Throws the FileNotFoundException if the files aren't found
if (!file1.exists()) {
throw new FileNotFoundException("File \"file1.txt\" was not found.");
} else {
//do something
}
if (!file2.exists()) {
throw new FileNotFoundException("File \"file2.txt\" was not found.");
} else {
//do something
}
在另一个类中,如果文件丢失,我想捕获异常。
public class FileIO {
public static void main(String[] args) {
try {
//do stuff
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
如果只有一个文件丢失,这将非常有用。但是如果 file1 和 file2 都丢失了,我只捕获第一个丢失文件的异常,然后程序结束。我的输出是:
File "file1.txt" is not found.
如何捕获两者的异常?我希望它输出:
File "file1.txt" is not found.
File "file2.txt" is not found.
【问题讨论】:
标签: java try-catch filenotfoundexception throw throws