What Is an Exception?

What Is an Exception?

The term exception is shorthand for the phrase “exceptional event.”

術語異常是異常事件的簡寫。

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

定義:一個異常是一個事件,它發生在一個程序的執行期間,它打斷了程序指令的正常流程。

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

當一個錯誤發生在一個方法中,方法將會創建一個對象,並將這個對象交給運行時系統。這個對象被稱爲異常對象,包含了錯誤的信息,包括異常的類型和錯誤發生時程序的狀態。創建一個異常對象並把它交給運行時系統被稱爲拋出一個異常。

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).

在一個方法拋出異常後,運行時系統將嘗試找一些東西去處理這個異常。處理這個異常的一些東西的可能集合是方法(這些方法通過被調用而到達了發生錯誤的方法)的排序列表。這個方法列表亦被稱爲調用棧(見下圖)。


callstack
The call stack.

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

運行時系統從調用棧中查找一個包含了處理這個異常的代碼塊的方法。這個代碼塊被稱爲異常處理器。這個查找從發生錯誤的方法開始,以方法被調用的相反順序通過調用棧。當一個合適的處理器被找到,運行時系統將異常傳遞給這個處理器。只有在被拋出異常對象的類型匹配處理器可以處理的類型時,異常處理器才被認爲是合適的。

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.

被選中的異常處理器認爲是捕獲了這個異常。如果運行時系統徹底查找了調用棧上的所有方法,也沒有找到合適的異常處理器,運行時系統(程序)將會終止,見下圖。


errorOccurs
Searching the call stack for the exception handler.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章