【问题标题】:How to print multiple exceptions in an input file to an errors file?如何将输入文件中的多个异常打印到错误文件?
【发布时间】:2016-03-29 16:10:25
【问题描述】:

我现在正在上计算机科学 (java) 课程,我们的任务是创建一个程序,该程序从 input.txt 文件中读取整数(教授会有这个)并将所有整数打印到输出中。 txt 文件。任何异常/错误都需要打印到我们的程序创建的 errors.txt 文件中。 (我们现在正在课堂上学习异常)。

我的程序能够从输入文件中读取并仅将整数打印到 output.txt,但是我在打印所有可能发生的异常时遇到了问题。例如,如果输入文件的行之一是“abc”,它应该在 errors.txt 文件中打印一条消息,说明它不是整数。

我的程序发生的情况是,一旦抛出一个异常,即使有更多要打印的异常,它也不会继续打印出所有其他异常。它就在那个时候停止。

例如,像这样的:

try{        

            while (fileScan.hasNext())
            {
                num = fileScan.nextInt();
            }

    }catch(Exception e)
    {               
        erout.println(e); //prints the error to the file.
        fileScan.nextLine();
    }

erout 是 error.txt 文件的 PrintWriter 对象。文件扫描输入.txt。

我只是不确定如何让它遍历所有 input.txt 文件并跟踪它将抛出的所有异常,然后将所有这些打印到 error.txt 文件中。任何帮助将不胜感激,谢谢。 :)

【问题讨论】:

    标签: java exception


    【解决方案1】:

    您可以将while 循环移到try 语句之外。

    while (fileScan.hasNext())
    {
        try{        
    
                num = fileScan.nextInt();
    
        }catch(Exception e)
        {               
        erout.println(e); //prints the error to the file.
        fileScan.nextLine();
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要重新订购您的whiletry/catch

      List<Exception> exceptions = new ArrayList<>();
      while (fileScan.hasNext()) {
          try {
               num = fileScan.nextInt();
               // more code here to process num
          } catch (Exception e) {
               // Might also want to create a custom exception type to track
               // The line/file that the error occurred upon.
               exceptions.add(e);
               fileScan.nextLine();
          }
      }
      

      【讨论】:

      • 当,正如我在另一条评论中所说,这是一个非常愚蠢的错误。谢谢。 :)
      【解决方案3】:

      您所要做的就是在一段时间内移动 try/catch:

              while (fileScan.hasNext())
              {
                  try {
                      num = fileScan.nextInt();
                  }
                  catch (Exception e) {
                      erout.println(e); //prints the error to the file.
                      fileScan.nextLine();
                  } 
      
              }
      

      【讨论】:

      • 当,正如我在另一条评论中所说,这是一个非常愚蠢的错误。谢谢。 :)
      • 不用担心,学习时会发生。我敢肯定不会再发生了:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多