【发布时间】: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