簡單示例
class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}
public class A {
private static void fun() throws MyException {
throw new MyException("MyException in fun()");
}
public static void main(String args[]) {
try {
fun();
} catch (MyException e) {
e.printStackTrace(System.out);
}
}
}
finally
簡單示例
try {
fun();
} catch (MyException e) {
e.printStackTrace(System.out);
}
finally {
System.out.println("finally");
}
說明
- 無論是否拋出異常都會(huì)執(zhí)行finally桃笙。
- 不會(huì)被break、continue和return跳過
- 通常做一些錯(cuò)誤恢復(fù)操作沙绝,如:關(guān)閉網(wǎng)絡(luò)連接搏明,關(guān)閉文件讀寫。
繼承中的異常
- 子類重寫父類拋出異常的方法時(shí)的三種選擇:
- 拋出父類方法拋出的異常闪檬。
- 拋出父類方法拋出的異常的父類星著。
- 不拋出異常。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者