2016-07-17 33 views
0

Ich habe zwei Textdateien und ich möchte eine Ausnahme auslösen, wenn die Dateien nicht gefunden werden. Ich habe eine Klasse FileReader, die prüft, ob die Dateien existieren und in meinem Haupt versuche ich, die Ausnahme zu fangen.Wie fange ich FileNotFoundException für zwei Dateien?

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 
     } 

In einer anderen Klasse möchte ich die Ausnahme abfangen, wenn die Dateien fehlen.

public class FileIO { 

public static void main(String[] args) { 

    try { 
     //do stuff 
    } catch(FileNotFoundException e) { 
     System.out.println(e.getMessage()); 
    } 

Das funktioniert gut, wenn nur eine Datei fehlt. Aber wenn Datei1 und Datei2 fehlen, erhalte ich nur die Ausnahme für die erste fehlende Datei und dann endet das Programm. Meine Ausgabe ist:

File "file1.txt" is not found. 

Wie kann ich die Ausnahme für beide? Ich möchte, dass es ausgibt:

File "file1.txt" is not found. 
File "file2.txt" is not found. 

Antwort

2

Sie können die Fehlermeldung zuerst erstellen, bevor Sie die Ausnahme auslösen.

public FileReader() throws FileNotFoundException { 
    super(); 
    File file1 = new File("file1.txt"); 
    File file2 = new File("file2.txt"); 

    String message = ""; 

    if (!file1.exists()) { 
     message = "File \"file1.txt\" was not found."; 
    } 
    if (!file2.exists()) { 
     message += "File \"file2.txt\" was not found."; 
    } 

    //Throws the FileNotFoundException if the files aren't found 
    if (!messag.isEmpty()) { 
     throw new FileNotFoundException(message); 
    } 

    //do something 
+0

Brilliant. Vielen Dank. –