Documentation

The Java™ Tutorials
Hide TOC
How to Throw Exceptions如何抛出异常
Trail: Essential Java Classes
Lesson: Exceptions

How to Throw Exceptions如何抛出异常

Before you can catch an exception, some code somewhere must throw one.在捕获异常之前,某个地方的某些代码必须抛出一个异常。Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment.任何代码都可能引发异常:您的代码、来自其他人编写的包(如Java平台附带的包)或Java运行时环境的代码。Regardless of what throws the exception, it's always thrown with the throw statement.不管抛出异常的是什么,它总是与throw语句一起抛出。

As you have probably noticed, the Java platform provides numerous exception classes.您可能已经注意到,Java平台提供了许多异常类。All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.所有类都是Throwable类的后代,并且所有类都允许程序区分在程序执行期间可能发生的各种类型的异常。

You can also create your own exception classes to represent problems that can occur within the classes you write.您还可以创建自己的异常类来表示您编写的类中可能出现的问题。In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.事实上,如果您是包开发人员,您可能必须创建自己的异常类集,以允许用户区分包中可能发生的错误与Java平台或其他包中发生的错误。

You can also create chained exceptions.您还可以创建链接异常。For more information, see the Chained Exceptions section.有关更多信息,请参阅链式异常部分。

The throw Statementthrow语句

All methods use the throw statement to throw an exception.所有方法都使用throw语句来抛出异常。The throw statement requires a single argument: a throwable object.throw语句需要一个参数:可抛出对象。Throwable objects are instances of any subclass of the Throwable class.可抛出对象是Throwable类的任何子类的实例。Here's an example of a throw statement.下面是一个throw语句的示例。

throw someThrowableObject;

Let's look at the throw statement in context.让我们在上下文中看一下throw语句。The following pop method is taken from a class that implements a common stack object.以下pop方法取自实现公共堆栈对象的类。The method removes the top element from the stack and returns the object.该方法从堆栈中移除顶层元素并返回对象。

public Object pop() {
    Object obj;

    if (size == 0) {
throw new EmptyStackException();
    }

    obj = objectAt(size - 1);
    setObjectAt(size - 1, null);
    size--;
    return obj;
}

The pop method checks to see whether any elements are on the stack.pop方法检查堆栈上是否有任何元素。If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it.如果堆栈为空(其大小等于0),pop将实例化一个新的EmptyStackException对象(java.util的成员)并抛出它。The Creating Exception Classes section in this chapter explains how to create your own exception classes.本章中的创建异常类部分解释了如何创建自己的异常类。For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.现在,您需要记住的是,您只能抛出从java.lang.Throwable类继承的对象。

Note that the declaration of the pop method does not contain a throws clause.请注意,pop方法的声明不包含throws子句。EmptyStackException is not a checked exception, so pop is not required to state that it might occur.EmptyStackException不是选中的异常,因此不需要pop来声明它可能发生。

Throwable Class and Its SubclassesThrowable类及其子类

The objects that inherit from the Throwable class include direct descendants (objects that inherit directly from the Throwable class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable class).Throwable类继承的对象包括直接子对象(直接从Throwable类继承的对象)和间接子对象(从Throwable类的子对象或孙子对象继承的对象)。The figure below illustrates the class hierarchy of the Throwable class and its most significant subclasses.下图说明了Throwable类及其最重要的子类的类层次结构。As you can see, Throwable has two direct descendants: Error and Exception.正如您所看到的,Throwable有两个直接的后代:ErrorException

The Throwable class and its most significant subclasses.

The Throwable class.

Error Class错误类

When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error.当Java虚拟机中发生动态链接故障或其他硬故障时,虚拟机将抛出一个错误。Simple programs typically do not catch or throw Errors.简单程序通常不会捕获或抛出错误。

Exception Class异常类

Most programs throw and catch objects that derive from the Exception class.大多数程序抛出并捕获从Exception类派生的对象。An Exception indicates that a problem occurred, but it is not a serious system problem.Exception表示出现了问题,但不是严重的系统问题。Most programs you write will throw and catch Exceptions as opposed to Errors.您编写的大多数程序都会抛出并捕获Exception,而不是Error

The Java platform defines the many descendants of the Exception class.Java平台定义了Exception类的许多子类。These descendants indicate various types of exceptions that can occur.这些子体表示可能发生的各种类型的异常。For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size.例如,IllegalAccessException表示找不到特定方法,NegativeArraySizeException表示程序试图创建大小为负的数组。

One Exception subclass, RuntimeException, is reserved for exceptions that indicate incorrect use of an API.一个Exception子类RuntimeException是为指示API使用不正确的异常保留的。An example of a runtime exception is NullPointerException, which occurs when a method tries to access a member of an object through a null reference.运行时异常的一个示例是NullPointerException,当方法尝试通过null引用访问对象的成员时会发生此异常。The section Unchecked Exceptions — The Controversy discusses why most applications shouldn't throw runtime exceptions or subclass RuntimeException.未经检查的异常—争论部分讨论了为什么大多数应用程序不应该抛出运行时异常或子类RuntimeException


Previous page: Specifying the Exceptions Thrown by a Method
Next page: Chained Exceptions