如何捕获两个文件的FileNotFoundException?

时间:2016-07-17 05:15:20

标签: java try-catch filenotfoundexception throw throws

我有两个文本文件,如果找不到文件,我想抛出异常。我有一个类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.

1 个答案:

答案 0 :(得分:2)

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

python setup.py install