码迷,mamicode.com
首页 > 编程语言 > 详细

Java 异常处理 (Exception Handling)

时间:2016-09-16 14:09:54      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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 black 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 }

 

Java 异常处理 (Exception Handling)

标签:

原文地址:http://www.cnblogs.com/joycelee/p/5876315.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!