Java Exceptions

1. 常見錯誤分類

通常的,errors能夠分爲如下幾類:java

  • user input errors
  • device errors or physical limitations
  • code errors

2. 經常使用錯誤處理方式

2.1 error code

一種經常使用的錯誤處理方法是返回error code,由calling method根據error code作不一樣處理。安全

可是有些情形下error code並不方便使用,好比如何取分錯誤碼和與錯誤碼相同的有效值。app

2.2 exception handling

The mission of exception handling is to transfer control from where the error occured to an error handler that can deal with the situation.ide

當出現錯誤時,程序應當恢復到某個安全狀態並從新來過,或者保存當前工做安全退出,可是這並不容易,關鍵就是程序控制權如何從觸發錯誤的地方跳轉處處理錯誤的地方。this

Java allows every method an alternative exit path if it is unable to complete its task in the normal way:編碼

  • 首先,throws an object that encapsulates the error information
  • 而後,the exception-handling mechanism begins its search for an exception handler that can deal with this particular error condition
  • 注意,這條alternative exit path與正常的程序邏輯無關,the method exits immediately, and it does not return its normal value, and the execution does not resume at the code that called the method

3. Java exception hierarchy

3.1 Throwable

Throwable是整個Java exception hierarchy的基類,其下分爲:code

  • Error
  • Exception

3.2 Error

the error hierarchy describes internal errors and resource exhaustion situations inside the Java runtime system.orm

You should not throw an object of this type. There is little you can do if sucn an internal error occurs, beyond notifying the user and trying to terminate the program gracefully.ip

3.3 Exception

Exception能夠分爲兩類:input

  • RuntimeException
  • 其餘

RuntimeException意味着編碼錯誤,好比
a bad cast, an out-of-bounds array access, a null pointer access等。

其餘Exception通常是出現了某種意外,some bad things happened, 好比,打開一個不存在的文件。

爲何打開不存在的文件不是RuntimeException?由於這不是你的代碼能控制的,你先校驗文件是否存在也沒用,可能你校驗時是存在的,但你打開時就不存在了。

4. Checked exception vs unchecked exception

Error和RuntimeException這兩支,咱們稱爲unchecked exception.

除Error和RuntimeException這兩支外的其餘Exception,咱們稱爲checked exception.

The compiler checks that you provide exception handlers for all checked exceptions:

  • 對於Error,你無能爲力,因此是unchecked exception
  • 對於RuntimeException,編碼錯誤是你的責任,你應當避免它們出現,因此也是unchecked exception
  • 對於其餘exceptions,你必須作好處理它們的準備,因此是checked exception

5. Checked exception declaration

對於你的方法可能拋出的checked exceptions,你必須在method declaration中經過throws聲明出來。

若是可能拋出多個checked exceptions,那麼須要都列出來,使用逗號分隔。

public Image loadImage(String name) throws FileNotFoundException, EOFException {...}

注意,unchecked exception不該當出如今你的throws聲明中:

  • 對於Error,你無能爲力
  • 對於RuntimeException,你應當避免它們出現,而不是聲明可能拋出它們。

6. Throw an exception

如何拋出exception呢?很簡單:

  • find an appropriate exception class
  • make an object of that class
  • throw it

沒有合適的standard exception class可用?沒有關係,你能夠自定義一個

class FileFormatException extends IOException {
    public FileFormatException() {}
    public FileFormatException(String gripe) {
        super(gripe);
    }
}

通常的,咱們爲自定義的exception class提供兩個constructors:a default constructor and a constructor with a detailed message.

7. Catch exceptions

try {
    xxx
} catch (ExceptionType1 | ExceptionType 2 e) {
    xxx
} catch (ExceptionType3 e) {
    xxx
}

對於checked exceptions,若是你知道如何處理它們,那麼你能夠catch它們,這樣就不用拋出它們了。

As a general rule, you should catch those exceptions that you know how to handle and propagate those that you do not know how to handle.

8. Rethrow exceptions

try {
    xxx
} catch (SQLException e) {
    throw new ServletException("xxx error").initCause(e);
}

這是rethrow exception的經常使用方式。經過這種方式,咱們能夠包裝出一個更抽象的exception,或者把一個checked exception轉換成一個RuntimeException.

9. finally

try {
    try {
        xxx
    } finally {
        xxx
    }
} catch (Exception e) {
    xxx
}

the inner try block has a single responsibility: to make sure that the resources are released

the outer try block has a single responsibility: to ensure that errors are reported.

注意,the body of the finally clause is intended for cleaning up resources. Don't put statements that change the control flow (return, throw, break, continue) inside a finally clause.

10. try-with-Resources

try (Resource res = xxx) {
    xxx
}

從Java 7開始,try-finally結構能夠簡化爲try-with-Resources.

要求Resource必須是AutoCloseable的實現類,when the try block exits, then res.close() is called automatically.

A difficulty arises when the try block throws an exception and the close method also throws an exception. The original exception is rethrown, and any exceptions thrown by close methods are considered "suppressed". They are automatically caught and added to the original exception with the addSuppressed method.

相關文章
相關標籤/搜索