Search code examples
javaexceptionexit-code

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


I am trying to figure out how to continue a code even after an exception is caught. Imagine that I have a text file filled with numbers. I want my program to read all those numbers. Now, lets say there is a letter mixed in there, is it possible for the exception to be caught, and then the code continues the loop? Would I need the Try and catches within a do-while loop? Please provide me with your ideas, I'd greatly appreciate it. I have provided my code just in case:

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;

    }

Solution

  • Declare your try-catch block inside your loop, so that loop can continue in case of exception.

    In your code, Scanner.nextDouble will throw InputMismatchException if the next token cannot be translated into a valid double value. That is that exception you would want to catch inside your loop.