繁体   English   中英

为什么捕获异常后我的Java程序退出?

[英]Why does my Java program exit after an exception is caught?

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

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块,以便在异常情况下该循环可以继续进行。

在您的代码中,如果下一个标记不能转换为有效的double值,则Scanner.nextDouble将引发InputMismatchException 那就是您想在循环中捕获的异常。

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

是的。 这些家伙说对了。 如果将try-catch放入循环中,则异常将保留在循环“内部”。 但是,现在的处理方式是,当引发异常时,该异常将“跳出”循环并继续进行,直到到达try / catch块为止。 像这样:

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

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

如果要在捕获异常后继续:

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

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

  3. 如果要在任何类型的异常之后继续执行,请捕获另一个通用Exception。 如果要在通用Exception的情况下退出,则可以通过捕获它来返回return。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM