Documentation

The Java™ Tutorials
Hide TOC
Chained Exceptions链式异常
Trail: Essential Java Classes
Lesson: Exceptions
Section: How to Throw Exceptions

Chained Exceptions链式异常

An application often responds to an exception by throwing another exception.应用程序通常通过抛出另一个异常来响应异常。In effect, the first exception causes the second exception.实际上,第一个异常会导致第二个异常。It can be very helpful to know when one exception causes another.了解一个异常何时导致另一个异常非常有帮助。Chained Exceptions help the programmer do this.链式异常有助于程序员做到这一点。

The following are the methods and constructors in Throwable that support chained exceptions.下面是Throwable中支持链式异常的方法和构造函数。

Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)

The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception.initCauseThrowable构造函数的Throwable参数是导致当前异常的异常。getCause returns the exception that caused the current exception, and initCause sets the current exception's cause.getCause返回导致当前异常的异常,initCause设置当前异常的原因。

The following example shows how to use a chained exception.下面的示例演示如何使用链接异常。

try {

} catch (IOException e) {
    throw new SampleException("Other IOException", e);
}

In this example, when an IOException is caught, a new SampleException exception is created with the original cause attached and the chain of exceptions is thrown up to the next higher level exception handler.在本例中,当捕获IOException时,将创建一个新的SampleException异常,并附加原始原因,然后将异常链抛出到下一个更高级别的异常处理程序。

Accessing Stack Trace Information访问堆栈跟踪信息

Now let's suppose that the higher-level exception handler wants to dump the stack trace in its own format.现在让我们假设高级异常处理程序希望以自己的格式转储堆栈跟踪。


Definition: A stack trace provides information on the execution history of the current thread and lists the names of the classes and methods that were called at the point when the exception occurred.堆栈跟踪提供有关当前线程的执行历史记录的信息,并列出在异常发生时调用的类和方法的名称。A stack trace is a useful debugging tool that you'll normally take advantage of when an exception has been thrown.堆栈跟踪是一个有用的调试工具,在抛出异常时,您通常会利用它。

The following code shows how to call the getStackTrace method on the exception object.下面的代码显示了如何在exception对象上调用getStackTrace方法。

catch (Exception cause) {
    StackTraceElement elements[] = cause.getStackTrace();
    for (int i = 0, n = elements.length; i < n; i++) {       
        System.err.println(elements[i].getFileName()
            + ":" + elements[i].getLineNumber() 
            + ">> "
            + elements[i].getMethodName() + "()");
    }
}

Logging API日志API

The next code snippet logs where an exception occurred from within the catch block.下一个代码段记录catch块中发生异常的位置。However, rather than manually parsing the stack trace and sending the output to System.err(), it sends the output to a file using the logging facility in the java.util.logging package.但是,它不是手动解析堆栈跟踪并将输出发送到System.err(),而是使用java.util.logging包中的日志功能将输出发送到文件。

try {
    Handler handler = new FileHandler("OutFile.log");
    Logger.getLogger("").addHandler(handler);
    
} catch (IOException e) {
    Logger logger = Logger.getLogger("package.name"); 
    StackTraceElement elements[] = e.getStackTrace();
    for (int i = 0, n = elements.length; i < n; i++) {
        logger.log(Level.WARNING, elements[i].getMethodName());
    }
}

Previous page: How to Throw Exceptions
Next page: Creating Exception Classes