首页 > 编程 > Java > 正文

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

2019-11-17 06:04:19
字体:
来源:转载
供稿:网友
1、不能在finally块中执行return,continue等语句,否则会把异常“吃掉”;
2、在try,catch中假如有return语句,则在执行return之前先执行finally块
 
请大家下面的例子:

  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.     public static boolean test() throws Exception {
  12.         try {
  13.             throw new Exception("Something error");// 第1步.抛出异常
  14.         } catch (Exception e) {// 第2步.捕捉的异常匹配(声明类或其父类),进入控制块
  15.             System.out.println("Exception from e");// 第3步.打印
  16.             return false;// 第5步. return前控制转移到finally块,执行完后再返回(这一步被吃掉了,不执行)
  17.         } finally {
  18.             return true// 第4步. 控制转移,直接返回,吃掉了异常
  19.         }
  20.     }
  21.     
  22.     public static void doThings(int i)
  23.     {
  24.      try
  25.      {

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表