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

时间:2015-10-12 03:40:18

标签: java exception exception-handling exit-code

我试图弄清楚即使在捕获异常后如何继续代码。想象一下,我有一个充满数字的文本文件。我希望我的程序读取所有这些数字。现在,假设有一个字母混合在那里,是否有可能捕获异常,然后代码继续循环?我是否需要在do-while循环中尝试和捕获?请告诉我你的想法,我非常感激。我提供了我的代码以防万一:

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;

    }

4 个答案:

答案 0 :(得分:3)

在循环中声明你的try-catch块,以便在异常情况下循环可以继续。

在您的代码中,如果下一个令牌无法转换为有效的double值,Scanner.nextDouble将抛出InputMismatchException。那就是你想要在循环中捕获的异常。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

是的。这些家伙说得对。如果你把你的try-catch放在循环中,异常就会留在"内部"循环。但是你现在拥有它的方式,当抛出异常时,异常将会突然出现"循环并继续前进,直到它到达try / catch块。像这样:

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

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

答案 3 :(得分:0)

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

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

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

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

相关问题