【问题标题】:How to catch FileNotFoundException for two files?如何捕获两个文件的 FileNotFoundException?
【发布时间】:2016-07-17 05:15:19
【问题描述】:

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

【问题讨论】:

    标签: java try-catch filenotfoundexception throw throws


    【解决方案1】:

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

    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
    

    【讨论】:

    • 太棒了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多