2016-07-17 33 views
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. 

回答

2

您可以在抛出异常之前构造错误消息。

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

辉煌。谢谢。 –