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发行说明。
When faced with choosing the type of exception to throw, you can either use one written by someone else the Java platform provides a lot of exception classes you can use or you can write one of your own.在选择要抛出的异常类型时,您可以使用其他人编写的异常类型Java平台提供了许多可以使用的异常类或者你也可以自己写一套。You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.如果您对以下任何一个问题的答案是肯定的,您应该编写自己的异常类;否则,您可能会使用其他人的。
Suppose you are writing a linked list class.假设您正在编写一个链表类。The class supports the following methods, among others:除其他外,该类支持以下方法:
objectAt(int n)
n
th position in the list.n
个位置的对象。firstObject()
indexOf(Object o)
Object
and returns its position in the list.Object
并返回其在列表中的位置。The linked list class can throw multiple exceptions, and it would be convenient to be able to catch all exceptions thrown by the linked list with one exception handler.链表类可以抛出多个异常,使用一个异常处理程序捕获链表抛出的所有异常会很方便。Also, if you plan to distribute your linked list in a package, all related code should be packaged together.此外,如果您计划在包中分发链接列表,那么所有相关代码都应该打包在一起。Thus, the linked list should provide its own set of exception classes.因此,链表应该提供自己的一组异常类。
The next figure illustrates one possible class hierarchy for the exceptions thrown by the linked list.下一个图说明了链表引发的异常的一个可能的类层次结构。
Example exception class hierarchy.示例异常类层次结构。
Any 任何Exception
subclass can be used as the parent class of LinkedListException
.Exception
子类都可以用作LinkedListException
的父类。However, a quick perusal of those subclasses shows that they are inappropriate because they are either too specialized or completely unrelated to 然而,快速阅读这些子类会发现它们是不合适的,因为它们要么过于专业化,要么与LinkedListException
.LinkedListException
完全无关。Therefore, the parent class of 因此,LinkedListException
should be Exception
.LinkedListException
的父类应该是Exception
。
Most applets and applications you write will throw objects that are 您编写的大多数小程序和应用程序都会抛出属于Exception
s.Exception
的对象。Error
s are normally used for serious, hard errors in the system, such as those that prevent the JVM from running.Error
通常用于系统中严重的硬错误,例如那些阻止JVM运行的错误。
Exception
to the names of all classes that inherit (directly or indirectly) from the Exception
class.Exception
附加到从Exception
类继承(直接或间接)的所有类的名称中。