Java编程中异常处理的特殊情况

分类: J2SE   出处:iocblog整理  更新时间:2008-11-23   添加到收藏  

1、不能在finally块中执行return,continue等语句,否则会把异常“吃掉”;
2、在try,catch中如果有return语句,则在执行return之前先执行finally块
 
请大家下面的例子:
[iocblog.net 来源]
 [iocblog.net 来源]

  1. public class trytest {
  2.     public static void main(string[] args) {
  3.         try {
  4.             system.out.println(trytest.test());// 返回结果为true其没有任何异常
  5.         } catch (exception e) {
  6.             system.out.println("exception from main");
  7.             e.printstacktrace();
  8.         }
  9.         dothings(0);
  10.     }
  11.  
  12.     public static boolean test() throws exception {
  13.         try {
  14.             throw new exception("something error");// 第1步.抛出异常
  15.         } catch (exception e) {// 第2步.捕获的异常匹配(声明类或其父类),进入控制块
  16.             system.out.println("exception from e");// 第3步.打印
  17.             return false;// 第5步. return前控制转移到finally块,执行完后再返回(这一步被吃掉了,不执行)
  18.         } finally {
  19.             return true// 第4步. 控制转移,直接返回,吃掉了异常
  20.         }
  21.     }
  22.     
  23.     public static void dothings(int i)
  24.     {
  25.      try
  26.      {
  27.       if(i==0)
  28.       {
  29.        //在执行return之前会先执行finally
  30.        return;
  31.       }
  32.       int t=100/i;
  33.       system.out.println(t);
  34.      }catch(exception ex)
  35.      {
  36.       ex.printstacktrace();
  37.      }
  38.      finally
  39.      {
  40.       system.out.println("finally");
  41.      }
  42.     }
  43. }

Tag: 异常处理



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。