链接异常处理(Chained exceptions)对于Java 1.4而言还是个新东西,但程序员已经多年使用它,程序员要么自己编写这一方面的代码,要么利用第三方函数。现在链接异常处理已经成为标准API的其中重要的一部分。
链接异常处理非常有用,因为在异常发生之后,它们可以提供最及时的异常原因查看并处理之。虽然你可以通过调用当前异常的getCause方法(如下)来获得发生异常的原因根源,但你通常不会这样做的。
Throwable t = e.getCause();
当你想打印一个异常的堆栈跟踪时,如果已经存在异常原因,则原因的堆栈跟踪将会被打印,如果原因之中又包含着原因,则就打印被包含着的原因堆栈跟踪,如此类推。这里是带有原因的一个异常产生的堆栈跟踪,结果是打印堆栈跟踪:
public class ChainedTip {
public static void main(String args[]) {
try {
foo();
}
catch(TipException e) {
e.printStackTrace();
}
}
public static void foo() throws TipException {
try {
FileInputStream in = new FileInputStream("not.there");
}
catch (IOException e) {
throw new TipException(e);
}
}
}
tips.TipException: java.io.FileNotFoundException: not there (The system cannot find the file specified)
at tips.ChainedTip.foo(ChainedTip.java:21)
at tips.ChainedTip.main(ChainedTip.java:9)
Caused by: java.io.FileNotFoundException: not.there (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at tips.ChainedTip.foo(ChainedTip.java:18)
... 1 more
以"Caused by:"为开始的行表示TipException异常的原因。
