【问题标题】:Why does my Java program exit after an exception is caught?为什么我的 Java 程序在捕获到异常后退出?
【发布时间】:2023-03-15 16:44:01
【问题描述】:

我试图弄清楚即使在捕获到异常后如何继续执行代码。想象一下,我有一个用数字填充的文本文件。我希望我的程序能够读取所有这些数字。现在,假设其中混入了一个字母,是否有可能捕获异常,然后代码继续循环?我需要在 do-while 循环中使用 Try 和 catchs 吗?请提供您的想法,我将不胜感激。我提供了我的代码以防万一:

NewClass newInput = new NewClass();
    infile2 = new File("GironEvent.dat");
    try(Scanner fin = new Scanner (infile2)){
        /** defines new variable linked to .dat file */
         while(fin.hasNext())
         {
             /** inputs first string in line of file to variable inType */
             inType2 = fin.next().charAt(0);
             /** inputs first int in line of file to variable inAmount */
             inAmount2 = fin.nextDouble();

             /** calls instance method with two parameters */
             newInput.donations(inType2, inAmount2);
             /** count ticket increases */
             count+=1;
         }
         fin.close();
     }
    catch (IllegalArgumentException ex) {
                 /** prints out error if exception is caught*/
                 System.out.println("Just caught an illegal argument exception. ");
                 return;
             }
    catch (FileNotFoundException e){
        /** Outputs error if file cannot be opened. */
        System.out.println("Failed to open file " + infile2  );
        return;

    }

【问题讨论】:

  • 您可以在循环中放置一个try-catch块,其中catch块只记录错误并跳转到循环的下一个迭代。

标签: java exception exception-handling exit-code


【解决方案1】:

在循环中声明你的 try-catch 块,这样循环可以在出现异常时继续。

在您的代码中,如果下一个标记无法转换为有效的双精度值,Scanner.nextDouble 将抛出 InputMismatchException。这就是您希望在循环中捕获的异常。

【讨论】:

    【解决方案2】:

    是的,我会将你的 try/catch 放在你的 while 循环中,尽管我认为你需要删除你的 return 语句。

    【讨论】:

      【解决方案3】:

      是的。这些人说得对。如果您将 try-catch 放在循环内,则异常将保留在循环“内部”。但是按照您现在的方式,当抛出异常时,异常将“跳出”循环并继续运行,直到到达 try/catch 块。像这样:

          try                   while  
           ^
           |
         while          vs       try
           ^                      ^
           |                      |
      Exception thrown       Exception thrown
      

      在您的情况下,您需要 两个 try/catch 块:一个用于打开文件(循环外),另一个用于读取文件(循环内)。

      【讨论】:

        【解决方案4】:

        如果你想在捕获异常后继续:

        1. 遇到异常时删除return语句。

        2. 在 while 循环内部和外部捕获所有可能的异常,因为当前的 catch 块仅捕获 2 个异常。使用 Scanner API 查看可能的异常。

        3. 如果您想在任何类型的异常之后继续,请再捕获一个通用 Exception 。如果你想在泛型异常的情况下退出,你可以通过捕获它来返回。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-19
          • 2016-02-09
          • 1970-01-01
          • 2016-02-10
          相关资源
          最近更新 更多