Reputation: 71
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;
}
Upvotes: 0
Views: 1967
Reputation: 38910
If you want continue after catching exception:
Remove return statement when you encounter exception.
Catch all possible exceptions inside and outside while loop since your current catch block catches only 2 exceptions. Have a look at possible exceptions with Scanner API.
If you want to continue after any type of exception, catch one more generic Exception . If you want to exit in case of generic Exception, you can put return by catching it.
Upvotes: 0
Reputation: 3581
Yep. These guys have it right. If you put your try-catch inside the loop, the exception will stay "inside" the loop. But the way you have it now, when an exception is thrown, the exception will "break out" of the loop and keep going until it reaches the try/catch block. Like so:
try while
^
|
while vs try
^ ^
| |
Exception thrown Exception thrown
In your case you want two try/catch blocks: one for opening the file (outside the loop), and another for reading the file (inside the loop).
Upvotes: 0
Reputation: 455
Yes, I would put your try/catch in your while loop, although I think you'd need to remove your return statement.
Upvotes: 0
Reputation: 4154
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.
Upvotes: 3