Java異常處理機制,帶你走進程序員的完美世界。
Error類
程序無法處理的錯誤,其超出了應用程序的控制和處理能力,表示運行應用程序中嚴重的問題,多數與代碼編寫者無關,為JVM出現的問題,常見的有OutOfMemoryError,異常發生時,JVM一般選擇線程終止;Exception類
應用程序中可能的可預測和可恢復的問題,一般發生在特定方法和特定操作中,重要子類為RuntimeException;運行時異常和非運行時異常
運行時異常,是RuntimeException類及其子類,常見的有NullPointerException、ArrithmeticException和ClassNotFoundException,原則上不進行捕獲和拋出,其本質上為程序邏輯問題,期待程序員檢查后恢復;
非運行時異常,是RuntimeException以外的異常,發生在編譯時期,需要進行try...catch...finally或者throws拋出;檢查異常和未檢查異常
檢查異常(即非運行時異常):由程序不能控制的無效外界環境決定(數據庫問題,網絡異常,文件丟失等),與非運行時異常處理相同;
未檢查異常(Error和運行時異常):程序自身的瑕疵和邏輯錯誤,在運行時發生,與運行時異常處理相同;try...catch...finally使用原則
1)try代碼塊中發生異常,生成異常對象,返回對象引用,程序代碼終止;其后可以接零個或者多個catch代碼塊,沒有catch代碼塊,必須接一個finally代碼塊;
2)多個catch代碼塊,通常只能命中一個;
3)finally代碼塊常用于關閉資源,且不處理返回值;finally塊中發生異常,前面代碼使用System.exit()退出程序,程序所在線程死亡,關閉CPU,此四種情況,不執行finally代碼塊;throw和throws區別
throws為方法拋出異常,由方法調用者處理,與方法調用者處理方式無關;
throw為語句拋出異常,不可單獨使用,與try...catch和throws配套使用;return語句與Java異常處理機制
finally中包含return語句,等同于告訴編譯器該方法無異常,即使存在異常,調用者也會捕獲不到異常,值得注意!
Java中處理異常中return關鍵字
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