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
Throwable
to 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 theThrowable
object
Send a stacktrace to log4j: log.error( "failed!", e );