The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
The term exception is shorthand for the phrase "exceptional event."“异常”一词是“异常事件”一词的简写
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.调用堆栈。
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.如果运行时系统彻底搜索调用堆栈上的所有方法,而没有找到适当的异常处理程序,如下图所示,则运行时系统(以及程序)终止。
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.您可以在例外的优点部分了解更多信息。