问题描述:
package Demo3;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Pri {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
double sum = 0;
int b;
int count=0;
while(true){
try {
b=scanner.nextInt();
if(b==0){
break;
}
sum+=b;
count++;
} catch (InputMismatchException ex) {
System.out.printf("略过非数字格式,%s%n",scanner.nextInt());
}
}
System.out.printf("平均 %.2f%n",sum/count);
}
}
你这个异常不是在try块中抛出的。
看一下你的代码,在try块中执行到读取输入时,假如输入的是不合规范的内容,引发了异常,这时程序跳转到catch块中执行,以上流程你没有异议吧?
注意,关键在这里:catch块中的语句是, System.out.printf("略过非数字格式,%s%n",scanner.nextInt());
这里你又用了scanner.nextInt(),所以,再一次引发了InputMismatchException异常,而这一次很不幸地没有相关语句来捕获它,所以就在控制台抛出了。
以上介绍了“Java执行时发生异常,但是无法跳到Catch异常区块,异常类型InputMismatchException。”的问题解答,希望对有需要的网友有所帮助。