異常指的是程式運行期間所出現的錯誤,運行時出錯可依照編譯器所顯示出的錯誤訊息及行號來了解錯誤發生的原因
下圖為異常throwable類的子類分支圖
1. Error異常為自身無法解決的錯誤,是JVM拋出的異常,有動態連結錯誤、JVM錯誤...等,程式對其錯誤並不處理,無法使用try、chtch處理該異常
2. Exception是自身可以處理的錯誤,需要用try、catch處理異常時所發生的結果,屬於異常類的父類,一般需要進行try、catch進行處理 ,若在API文檔中看到有throws的方法,則必須要用try、catch處理
3. RuntimeException屬於經常出現的錯誤,可以忽略,不使用try、catch也可以,此類屬於特殊異常類,如被0除、陣列超過索引...等,若對此異常進行處理,容易影響程式的可讀性和執行效率
語法為如下:
| public class TestException { public static void main(String[] args) { TestException te = new TestException(); te.ae(0); } void ae (int i) throws ArithmeticException { if (i == 0){ System.out.println("被除數不可為0"); } } } |
異常和繼承之間的關係,在繼承後子類重寫方法時,必須拋出與父類方法中一模一樣的異常,否則就是不拋異常,如下所示:
public class TestCase {
public void TestCase() throws IOException {
......................
}
}
class Test_1 extends TestCase {
public void TestCase() Exception {
//錯誤,拋出異常與父類方法不同
.......................
}
}
class Test_2 extends TestCase {
public void TestCase() FileNotFoundException {
//錯誤,拋出異常與父類方法不同
.......................
}
}
class Test_3 extends TestCase {
public void TestCase() IOException, NumberFormatException {
//錯誤,拋出異常與父類方法不同
.......................
}
}
class Test_4 extends TestCase {
public void TestCase() IOException {
//正確,拋出異常與父類方法相同
.......................
}
}
