A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wenyu 中级黑马   /  2015-2-26 16:48  /  1069 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

关于异常的try catch finnally的处理方式,都说finnally里的内容是一定会执行的,比如
  1. class Demo
  2. {
  3.         public static void main (String [] args){
  4.                 int a = 100;
  5.                 int b = 13;
  6.                 try
  7.                 {       
  8.                         int c = a/b;
  9.                         System.out.println(c);
  10.        
  11.                 }
  12.                 finally{
  13.                         System .out.println("finnally内容");
  14.                 }

  15.         }
  16. }
复制代码

但是如果在try里加入了系统退出,finnally里的内容就不会被执行了:
  1. class Demo
  2. {
  3.         public static void main (String [] args){
  4.                 int a = 100;
  5.                 int b = 13;
  6.                 try
  7.                 {       
  8.                         int c = a/b;
  9.                         System.out.println(c);
  10.                         System.exit(0);
  11.                 }
  12.                 finally{
  13.                         System .out.println("finnally内容");
  14.                 }

  15.         }
  16. }
复制代码



评分

参与人数 1技术分 +1 收起 理由
万合天宜 + 1 加油~~

查看全部评分

3 个回复

倒序浏览
还没有执行到finally你就让程序停止运行了当然不会再运行程序了,如果你保持程序一直处在运行状态finally是会被执行的,一般说的是try里面或者catch里面有return的情况下,finally会在return之前运行,但是finally的执行不会影响return的返回值。
  1. public static int tryit() {
  2.                
  3.                 int a = 1;
  4.                 try{
  5.                         System.out.println("try:" + a);
  6.                         return a;
  7.                 } finally {
  8.                         a ++;
  9.                         System.out.println("finally:" + a);
  10.                 }
  11.         }
复制代码

在main里调用:
  1. System.out.println("return:" + tryit());
复制代码


结果是:
  1. try:1
  2. finally:2
  3. return:1
复制代码

评分

参与人数 1技术分 +1 收起 理由
万合天宜 + 1 很给力!

查看全部评分

回复 使用道具 举报
lz这个问题很好!“finally一定会被执行”是一个含糊不严谨的说法。还是Java官方的the Java tutorial说得清楚:

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

也就是说,如果JVM退出了,或者try/finally所在的线程被中断了,那么finally块就可能不会被执行。另外,官方tutorial用的是“may not”,并没有说在JVM退出或线程中断时finally就一定不会执行,这可能跟JVM的实现规范有关,具体要参考JVM specification和Java language specification两份文档

点评

你好牛逼~~  发表于 2015-2-26 19:31

评分

参与人数 1黑马币 +3 收起 理由
万合天宜 + 3 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马