0
2つのテキストファイルがあり、ファイルが見つからない場合は例外をスローしたいと思います。ファイルが存在するかどうかをチェックし、私のメインで例外をキャッチしようとするクラスFileReaderがあります。2つのファイルの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());
}
これは、1つのファイルだけが不足している場合に有効です。しかし、file1とfile2の両方が見つからない場合は、最初に見つからなかったファイルの例外を検出し、プログラムが終了します。私の出力は:
File "file1.txt" is not found.
私は両方の例外をキャッチすることができますか?私は出力します:
File "file1.txt" is not found.
File "file2.txt" is not found.
ブリリアント。ありがとうございました。 –