参考:http://javcoder.iteye.com/blog/1131003
public class TCF { // 1.进入try语句块,finally中的代码都会执行。 // 2.finally块中避免使用return语句。原因: // (i)finally块中的return值会屏蔽掉try、catch中的return值。 // (ii)finally块中的return语句会屏蔽掉try、catch块中的异常信息。 // 3.finally块中避免再次抛出异常。原因: // (i)finally块中抛出的异常会屏蔽掉try、catch块中的异常。 // f1 : 1 static int f1() { try { return 1; } catch (Exception e) { return 2; // 不会执行,如果不添加会出现编译错误 (This method must return a result) } finally { System.out.print("f1"); } } // f2 : 3 // finally块中的return值会屏蔽掉try、catch中的return值。 static int f2() { try { return 1; } catch (Exception e) { } finally { System.out.print("f2"); return 3; } } // f3 : 2 static int f3() { try { throw new Exception("try error"); } catch (Exception e) { return 2; } finally { System.out.print("f3"); } } // f4 : catch error static int f4() throws Exception { try { throw new Exception("try error"); } catch (Exception e) { throw new Exception("catch error"); } finally { System.out.print("f4"); } } // f5 : 5 // finally块中的return语句会屏蔽掉try、catch块中的异常信息。 static int f5() { try { throw new Exception("try error"); } catch (Exception e) { throw new Exception("catch error"); } finally { System.out.print("f5"); return 5; } } // f6 : finally error // finally块中抛出的异常会屏蔽掉try、catch块中的异常。 static int f6() throws Exception { try { throw new Exception("try error"); } catch (Exception e) { throw new Exception("catch error"); } finally { System.out.print("f6"); throw new Exception("finally error"); } } public static void main(String[] args) { System.out.println(" : " + f1()); try { System.out.println(" : " + f2()); } catch (Exception e) { System.out.println(" : " + e.getMessage()); } try { System.out.println(" : " + f3()); } catch (Exception e) { System.out.println(" : " + e.getMessage()); } try { System.out.println(" : " + f4()); } catch (Exception e) { System.out.println(" : " + e.getMessage()); } try { System.out.println(" : " + f5()); } catch (Exception e) { System.out.println(" : " + e.getMessage()); } try { System.out.println(" : " + f6()); } catch (Exception e) { System.out.println(" : " + e.getMessage()); } } }