java异常处理的面试题

 1 package test;
 2 
 3 public class Test {
 4 
 5     public static int method(int i) throws Exception {
 6         try {
 7             return 100 / i;
 8         } catch (Exception ex) {
 9             throw new Exception("exception in a Method");
10         } finally {
11             System.out.printf("finally ");
12         }
13     }
14 
15     public static void main(String[] args) {
16         try {
17             method(0);
18         } catch (Exception ex) {
19             System.out.printf("exception in main ");
20         }
21         System.out.printf("finished");
22     }
23 }

运行结果:

根据结果分析的话

1)第7行生成异常对象并不会被所在的try catch捕获,而是返回给了它的上级调用者,被调用者的try catch捕获。

2)finally(),是无论如何都会被执行的即便try中有return也会执行只有一种方法让finally块不执行:System.exit()

关于fianlly()更多神奇的现象:http://www.cnblogs.com/lulipro/p/7504267.html#finally_return

原文地址:https://www.cnblogs.com/xdyixia/p/9404050.html