0
我有兩個文本文件,我想拋出一個異常,如果沒有找到文件。我有一個類FileReader,檢查文件是否存在,並在我的主要我試圖捕捉異常。如何捕獲兩個文件的FileNotFoundException?
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.
輝煌。謝謝。 –