Java 异常处理 (Exception Handling)

1. Never return in a finally statement.

If you return in a finally block then any Throwables that aren't caught will be completely lost.

e.g.

 1 // "Done!" will be print out, but there is no "Got it."
 2 public class Test {
 3   public static void main(String[] args) {
 4     try {
 5       doSomething();
 6       System.out.println("Done!");
 7     } catch (RuntimeException e) {
 8       System.out.println("Got it.");
 9     }
10   }
11   
12   public static void doSomething() {
13     try {
14       throw new RuntimeException();
15     } finally {
16       return;
17     }
18   }
19 }

 

2. If return in try/catch, changes in finally will not affect return value.

finally block run before return, but the return value will be copied.

 1 // print "123"
 2 public class Test {
 3     public static void main(String[] args) {
 4         System.out.println(getString());
 5     }
 6           
 7     public static String getString() {
 8         String str = "123";
 9         try {
10             throw new Exception();
11         } catch (Exception e) {
12             return str;
13         } finally {
14             str = "456";
15         }
16     }
17 }

 

posted @ 2016-09-16 13:16  Joyce-Lee  阅读(627)  评论(0编辑  收藏  举报