Java - Exception 異常處理
exception architecture

Error:程序無法處理的錯誤。Exception:程序本身可以處理的異常。- unchecked (
RuntimeException): All exception types that are direct or indirect subclasses of RuntimeException are unchecked exceptions. - checked: Java compiler enforces special requirements for checked exceptions (discussed momentarily). An exception’s type determines whether it’s checked or unchecked.
- unchecked (
| unchecked | checked | |
|---|---|---|
| mandatory inspection | x | v |
| spring auto rollback | v | x |
| example exception | NullPointerException | FileNotFoundException |
try-catch-finally
try-catch-finally 用法:
- try:用以捕獲異常,如果沒有
catch塊,則必須跟一個finally塊 - catch:用以處理
try捕獲的異常,可以接零個或多個catch塊 - finally:
- 無論是否捕獲或處理異常,
finally塊里的語句都會被執行 - 當在
try塊或catch塊遇到return語句時,finally語句將在方法返回之前執行,並且finally語句的返回值將會覆蓋原始的返回值
- 無論是否捕獲或處理異常,
public static int f(int value) {
try {
return value * value;
} finally {
if (value == 2) {
return 0;
}
}
}
如果調用f(2),返回值將是0,而不是4,因為finally語句的返回值覆蓋了try語句塊的返回值
try-with-resources
后用先关,先用后关
override exception
- 父類別
throws例外範圍 >= 子類別throws例外範圍 - 子類別可以丢
IOException,但子類別不可以丢Exception,因為Exception>IOException
exception message
Get exception message:
public string getMessage(): simple messagepublic string toString(): detailed messagepublic string getLocalizedMessage:- override this method with a subclass of
Throwableto generate localized information - if the subclass does not override the method, it is the same as the
getMessage()message
- override this method with a subclass of
public void printStackTrace(): print the exception information encapsulated by theThrowableobject
Send a stacktrace to log4j: log.error( "failed!", e );