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 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:

  1. public string getMessage(): simple message
  2. public string toString(): detailed message
  3. public 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
  4. public void printStackTrace(): print the exception information encapsulated by the Throwable object

Send a stacktrace to log4j: log.error( "failed!", e );