gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:04:14 25 4
gpt4 key购买 nike

我试图弄清楚如何在捕获异常后继续执行代码。想象一下我有一个充满数字的文本文件。我希望我的程序能够读取所有这些数字。现在,假设其中混有一个字母,是否有可能捕获异常,然后代码继续循环?我需要在 do-while 循环中使用 Try 和 catch 吗?请向我提供您的想法,我将不胜感激。我提供了我的代码以防万一:

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 block ,以便在发生异常时循环可以继续。

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

关于java - 为什么我的Java程序在捕获异常后退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33072927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com