Documentation

The Java™ Tutorials
Hide TOC
Creating Exception Classes创建异常类
Trail: Essential Java Classes
Lesson: Exceptions
Section: How to Throw Exceptions

Creating Exception Classes创建异常类

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.如果您对以下任何一个问题的答案是肯定的,您应该编写自己的异常类;否则,您可能会使用其他人的。

An Example一个例子

Suppose you are writing a linked list class.假设您正在编写一个链表类。The class supports the following methods, among others:除其他外,该类支持以下方法:

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.下一个图说明了链表引发的异常的一个可能的类层次结构。

A possible class hierarchy for the exceptions thrown by a linked list.

Example exception class hierarchy.示例异常类层次结构。

Choosing a Superclass选择超类

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 Exceptions.您编写的大多数小程序和应用程序都会抛出属于Exception的对象。Errors are normally used for serious, hard errors in the system, such as those that prevent the JVM from running.Error通常用于系统中严重的硬错误,例如那些阻止JVM运行的错误。


Note: For readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class.对于可读代码,最好将字符串Exception附加到从Exception类继承(直接或间接)的所有类的名称中。

Previous page: Chained Exceptions
Next page: Unchecked Exceptions — The Controversy