java try-catch以及循环的问题

来源:互联网 发布:哪里买域名 编辑:程序博客网 时间:2024/06/11 22:41

今天java基础课上碰到一个比较有意思的try-catch异常的问题,钻研了好久,分享出来大家讨论。

废话不多说,先上一段代码。

public class Demo3 {public static void main(String[] args) {int a = 0;int b = 0;int c = 0;boolean temp = true;Scanner sc = new Scanner(System.in);while (temp) {System.out.println("输入整数a和b");try {a = sc.nextInt();b = sc.nextInt();c = a + b;System.out.println("结果c=" + c);} catch (InputMismatchException ix) {System.out.println("输入错误,请输入整数");}}}}
大家普遍会认为,当发生异常时,执行catch语句,执行完以后返回while然后进入try,等待下一个a的输入。但是实际运行的时候却出现了无限的打印循环,如下图所示。


然后我研究了好一会,用eclipse的dbug功能做了测试,发现当出现异常时,反转回来在try语句上一闪而过,直接就执行了catch语句,并没有像我们想象的那样,等待下一个输入。

倒腾半天终于算是倒腾对了,只是做了一个小的微调,附上代码:

public class Demo3 {public static void main(String[] args) {int a = 0;int b = 0;int c = 0;boolean temp = true;while (temp) {Scanner sc = new Scanner(System.in);System.out.println("输入整数a和b");try {a = sc.nextInt();b = sc.nextInt();c = a + b;System.out.println("结果c=" + c);} catch (InputMismatchException ix) {System.out.println("输入错误,请输入整数");}}}}

运行效果图:



自己又做了几个实验对try-catch有了进一步了解。

1、try-catch放在循环里面,诺出现异常,执行完异常在次执行语句时,若没有重新进行变量的定义,try语句仍然判断上一次的输入,即在此出现异常,如此往复。(个人理解,还望大神指教)。

2、try-catch语句放在循环外面,出现异常会终止循环。

3、finally一定会执行,可用来跳出循环。

总结:

出现这种无限循环的问题有可能在不经意间,所以用循环的时候拿捏不准尽量不要使用异常,或者进行重点测试。


0 0
原创粉丝点击