通過前面的章節,我們深刻的理解了Java中方法、屬性、引用、關鍵字之間的聯繫,回顧:
但是明白了這些後,我們平常在寫程序的時候可能會出現一些我們不想要的Exception—異常。
我們常常說的異常是Exception,而不是error,error指運行環境出現的錯誤,是程序檢測不出來的,屬於系統的內部(例如JVM)錯誤。
例如資源不夠會出現OutOfMemoryError/StackOverflowError一樣,這類錯誤不該是讓程序去控制的,出現此類錯誤一般都是程序設計的問題。
#Exception
可以通過捕捉處理使程序繼續執行,是程序自身可以處理的異常。
不扯太多廢話,直接看一段代碼:摘自。
public class TestException {
public TestException() {}
boolean testEx() throws Exception {
boolean ret = true;
try {
ret = testEx1();
} catch (Exception e) {
System.out.println("testEx, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx, finally; return value=" + ret);
return ret;
}
}
boolean testEx1() throws Exception {
boolean ret = true;
try {
ret = testEx2();
if (!ret) {
return false;
}
System.out.println("testEx1, at the end of try");
return ret;
} catch (Exception e) {
System.out.println("testEx1, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx1, finally; return value=" + ret);
return ret;
}
}
boolean testEx2() throws Exception {
boolean ret = true;
try {
int b = 12;
int c;
for (int i = 2; i >= -2; i--) {
c = b / i;
System.out.println("i=" + i);
}
return true;
} catch (Exception e) {
System.out.println("testEx2, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx2, finally; return value=" + ret);
return ret;
}
}
public static void main(String[] args) {
TestException testException1 = new TestException();
try {
testException1.testEx();
} catch (Exception e) {
e.printStackTrace();
}
}
}
運行結果:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
你做對了嗎?
對於異常的詳細講解,這裏直接推薦一篇不錯的文章:
深入理解java異常處理機制。