Java 實例 - Finally的用法
Java 中的 Finally 關(guān)鍵一般與try一起使用,在程序進入try塊之后,無論程序是因為異常而中止或其它方式返回終止的,finally塊的內(nèi)容一定會被執(zhí)行 。
以下實例演示了如何使用 finally 通過 e.getMessage() 來捕獲異常(非法參數(shù)異常):
/* author by w3cschool.cc ExceptionDemo2.java */ public class ExceptionDemo2 { public static void main(String[] argv) { new ExceptionDemo2().doTheWork(); } public void doTheWork() { Object o = null; for (int i=0; i<5; i++) { try { o = makeObj(i); } catch (IllegalArgumentException e) { System.err.println ("Error: ("+ e.getMessage()+")."); return; } finally { System.err.println("都已執(zhí)行完畢"); if (o==null) System.exit(0); } System.out.println(o); } } public Object makeObj(int type) throws IllegalArgumentException { if (type == 1) throw new IllegalArgumentException ("不是指定的類型: " + type); return new Object(); } }
以上代碼運行輸出結(jié)果為:
都已執(zhí)行完畢 java.lang.Object@7852e922 Error: (不是指定的類型:1). 都已執(zhí)行完畢
更多建議: