我想知道如何在發生異常後繼續執行代碼。想象一下,我有一個充滿數字的文本文件。我想讓我的程序讀取所有這些數字。現在,假設有一個字母混合在一起,是否有可能捕獲異常,然後代碼繼續循環?我需要嘗試並捕獲一個do-while循環嗎?請給我提供你的想法,我非常感謝。我已經提供了我的代碼以防萬一:爲什麼我的Java程序在捕獲到異常後退出?
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塊只記錄錯誤並跳轉到下一次迭代循環。 – t0mppa