黑马程序员技术交流社区

标题: 关于异常的一个小问题 [打印本页]

作者: wenyu    时间: 2015-2-26 16:48
标题: 关于异常的一个小问题
关于异常的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. }
复制代码




作者: Hsidar    时间: 2015-2-26 16:59
还没有执行到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
复制代码

作者: fantacyleo    时间: 2015-2-26 17:10
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两份文档




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2