Documentation

The Java™ Tutorials
Hide TOC
What Is an Exception?什么是异常?
Trail: Essential Java Classes
Lesson: Exceptions

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.处理异常的一组可能的“something”是为获取发生错误的方法而调用的方法的有序列表。The list of methods is known as the call stack方法列表称为调用堆栈 (see the next figure).(请参见下图)。

The call stack showing three method calls, where the first method called has the exception handler.

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.如果运行时系统彻底搜索调用堆栈上的所有方法,而没有找到适当的异常处理程序,如下图所示,则运行时系统(以及程序)终止。

The call stack showing three method calls, where the first method called has the exception handler.

Searching the call stack for the exception handler.在调用堆栈中搜索异常处理程序。

Using exceptions to manage errors has some advantages over traditional error-management techniques.与传统的错误管理技术相比,使用异常管理错误具有一些优势。You can learn more in the Advantages of Exceptions section.您可以在例外的优点部分了解更多信息。


Previous page: Exceptions
Next page: The Catch or Specify Requirement