java try-catch以及循环的问题

来源:互联网 发布:淘宝女装尺码表模板 编辑:程序博客网 时间:2024/06/06 07:13

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

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

[java] view plaincopy
  1. public class Demo3 {  
  2.     public static void main(String[] args) {  
  3.         int a = 0;  
  4.         int b = 0;  
  5.         int c = 0;  
  6.         boolean temp = true;  
  7.         Scanner sc = new Scanner(System.in);  
  8.         while (temp) {        
  9.               
  10.             System.out.println("输入整数a和b");  
  11.             try {  
  12.                 a = sc.nextInt();  
  13.                 b = sc.nextInt();     
  14.                 c = a + b;  
  15.                 System.out.println("结果c=" + c);  
  16.             } catch (InputMismatchException ix) {  
  17.                 System.out.println("输入错误,请输入整数");                 
  18.             }             
  19.         }  
  20.           
  21.     }  
  22.   
  23. }  
大家普遍会认为,当发生异常时,执行catch语句,执行完以后返回while然后进入try,等待下一个a的输入。但是实际运行的时候却出现了无限的打印循环,如下图所示。


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

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

[java] view plaincopy
  1. public class Demo3 {  
  2.     public static void main(String[] args) {  
  3.         int a = 0;  
  4.         int b = 0;  
  5.         int c = 0;  
  6.         boolean temp = true;  
  7.           
  8.         while (temp) {        
  9.             Scanner sc = new Scanner(System.in);  
  10.             System.out.println("输入整数a和b");  
  11.             try {  
  12.                 a = sc.nextInt();  
  13.                 b = sc.nextInt();     
  14.                 c = a + b;  
  15.                 System.out.println("结果c=" + c);  
  16.             } catch (InputMismatchException ix) {  
  17.                 System.out.println("输入错误,请输入整数");                 
  18.             }             
  19.         }  
  20.           
  21.     }  
  22.   
  23. }  

运行效果图:



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

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

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

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

总结:

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

发表者:侯纪祥


0 0
原创粉丝点击