Java 實例 - Finally的用法
Java 中的 Finally 關鍵一般與try一起使用,在程式進入try塊之後,無論程式是因為異常而中止或其他方式返回終止的,finally塊的內容一定會被執行 。
以下實例演示了如何使用 finally 通過 e.getMessage() 來捕獲異常(非法參數異常):
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("都已執行完畢");
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();
}
}
以上代碼運行輸出結果為:
都已執行完畢 java.lang.Object@7852e922 Error: (不是指定的類型:1). 都已執行完畢