Java 异常处理 (Exception Handling)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)的主要内容,如果未能解决你的问题,请参考以下文章