Java: try/catch 与 InputMismatchException 在读取文件时创建无限循环
Java: try/catch with InputMismatchException creates infinite loop while reading of a file
我的任务是编写一个程序,将文件中的所有有效整数相加,并忽略任何非有效整数。我必须使用 Try and Catch。
File Numbers = new File("Numbers.txt");
Scanner readFile = null;
int i = 0;
int total= 0;
boolean success = false;
while(!success){
try {
readFile = new Scanner(Numbers);
while(readFile.hasNext()){
i = readFile.nextInt();
System.out.println(i);
total = i + total;
};
success = true;// Ends The loop
} catch (FileNotFoundException e1) {
System.err.println(Numbers.getName()+" does not exist");
}
catch(InputMismatchException e2){
System.err.println("Data incorrect type expecting an int found: " + readFile.nextLine());
readFile.next();
}
System.out.println("total is: " + total);
};
问题是程序陷入了无限循环,它没有跳过异常而是开始 again.The 任务看起来很简单,但我不知道为什么它不起作用?
假设将引发以下任何 FileNotFound 或 InputMismatchException 异常,那么您的程序不会将 success 更改为 true。因此它 returns 到外部 while 循环并读取同一个文件。因为什么都没有改变,同样的异常将再次抛出。
==> 无限循环。
为了解决这个问题,我建议将 try/catch 块移动到内部 while。
你陷入了无限循环,因为当异常发生时,success
变量没有将其值更改为 true
。为了执行某些操作 即使发生异常,您应该添加 finnaly
块。它可能看起来像这样:
try {
// do some stuff
} catch (Exception e) {
// catch the exception
} finally {
if (!readFile.hasNext()) success = true;
}
顺便说一下,从不这样做:catch (Exception e)
,我这样做只是为了举例。相反,总是捕获特定的异常。因为 Exception
是异常层次结构中最基本的 class ,所以它会赶上 所有 异常,除非你重新抛出它,否则你可能有 false "safiness"的感觉。当你想捕获所有异常时,你应该这样做:
try {
// do stuff
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace(); // or other approptiate action, i.e. log it.
}
我的任务是编写一个程序,将文件中的所有有效整数相加,并忽略任何非有效整数。我必须使用 Try and Catch。
File Numbers = new File("Numbers.txt");
Scanner readFile = null;
int i = 0;
int total= 0;
boolean success = false;
while(!success){
try {
readFile = new Scanner(Numbers);
while(readFile.hasNext()){
i = readFile.nextInt();
System.out.println(i);
total = i + total;
};
success = true;// Ends The loop
} catch (FileNotFoundException e1) {
System.err.println(Numbers.getName()+" does not exist");
}
catch(InputMismatchException e2){
System.err.println("Data incorrect type expecting an int found: " + readFile.nextLine());
readFile.next();
}
System.out.println("total is: " + total);
};
问题是程序陷入了无限循环,它没有跳过异常而是开始 again.The 任务看起来很简单,但我不知道为什么它不起作用?
假设将引发以下任何 FileNotFound 或 InputMismatchException 异常,那么您的程序不会将 success 更改为 true。因此它 returns 到外部 while 循环并读取同一个文件。因为什么都没有改变,同样的异常将再次抛出。
==> 无限循环。
为了解决这个问题,我建议将 try/catch 块移动到内部 while。
你陷入了无限循环,因为当异常发生时,success
变量没有将其值更改为 true
。为了执行某些操作 即使发生异常,您应该添加 finnaly
块。它可能看起来像这样:
try {
// do some stuff
} catch (Exception e) {
// catch the exception
} finally {
if (!readFile.hasNext()) success = true;
}
顺便说一下,从不这样做:catch (Exception e)
,我这样做只是为了举例。相反,总是捕获特定的异常。因为 Exception
是异常层次结构中最基本的 class ,所以它会赶上 所有 异常,除非你重新抛出它,否则你可能有 false "safiness"的感觉。当你想捕获所有异常时,你应该这样做:
try {
// do stuff
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace(); // or other approptiate action, i.e. log it.
}