ITPub博客

首页 > 应用开发 > Java > Java程序异常处理的特殊情况

Java程序异常处理的特殊情况

原创 Java 作者:vjvj110 时间:2022-05-10 03:56:46 0 删除 编辑

  1、不能在finally块中执行return,continue等语句,否则会把异常“吃掉”;   2、在try,catch中如果有return语句,则在执行return之前先执行finally块   请大家仔细看下面的例子: 以下是引用片段:public class TryTest { public static void main(String[] args) { try { System.out.println(TryTest.test());// 返回结果为true其没有任何异常 } catch (Exception e) { System.out.println("Exception from main"); e.printStackTrace(); } doThings(0); } public static boolean test() throws Exception { try { throw new Exception("Something error");// 第1步.抛出异常 } catch (Exception e) {// 第2步.捕获的异常匹配(声明类或其父类),进入控制块 System.out.println("Exception from e");// 第3步.打印 return false;// 第5步. return前控制转移到finally块,执行完后再返回(这一步被吃掉了,不执行) } finally { return true; // 第4步. 控制转移,直接返回,吃掉了异常 } } public static void doThings(int i) { try { if(i==0) { //在执行return之前会先执行finally return; } int t=100/i; System.out.println(t); }catch(Exception ex) { ex.printStackTrace(); } finally { System.out.println("finally"); } } } 阅读关于 Java 异常处理 特殊情况 的全部文章    1、不能在finally块中执行return,continue等语句,否则会把异常“吃掉”;   2、在try,catch中如果有return语句,则在执行return之前先执行finally块   请大家仔细看下面的例子: 以下是引用片段:public class TryTest { public static void main(String[] args) { try { System.out.println(TryTest.test());// 返回结果为true其没有任何异常 } catch (Exception e) { System.out.println("Exception from main"); e.printStackTrace(); } doThings(0); } public static boolean test() throws Exception { try { throw new Exception("Something error");// 第1步.抛出异常 } catch (Exception e) {// 第2步.捕获的异常匹配(声明类或其父类),进入控制块 System.out.println("Exception from e");// 第3步.打印 return false;// 第5步. return前控制转移到finally块,执行完后再返回(这一步被吃掉了,不执行) } finally { return true; // 第4步. 控制转移,直接返回,吃掉了异常 } } public static void doThings(int i) { try { if(i==0) { //在执行return之前会先执行finally return; } int t=100/i; System.out.println(t); }catch(Exception ex) { ex.printStackTrace(); } finally { System.out.println("finally"); } } } 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31495967/viewspace-2893167/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2017-10-14

  • 博文量
    13
  • 访问量
    6131