首页 > 代码库 > Java 异常处理 (Exception Handling)
Java 异常处理 (Exception Handling)
1. Never return in a finally statement.
If you return
in a finally
block then any Throwable
s 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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。