| |
链接异常处理(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异常的原因。 正如你所看到的,如果想知道,你可以从链接异常中得到大量的信息。实际上,链接异常就随带着丰富的信息。
当在一个嵌套类中产生异常时,你可以得到包含多页的堆栈跟踪结果,但实质上只包含一个错误内容。虽然这是链接异常处理的一个不足,但它还是值得使用的。
当建立一个自己的异常处理时,请充分利用链接异常处理,除了使用通常使用的构造器之外,还要编写两个构造器。
classtipexception extends exception { public tipexception() {}
public tipexception(string msg) { super(msg); }
public tipexception(string msg, throwable t) { super(msg, t); }
public tipexception(throwable t) { super(t); } }
通过执行包含throwable对象的两个构造器,可以实现链接异常处理。在这些构造器中,你可以将一些函数从throwable对象传递到上一层类中,并让其完成所有的任务。
链接异常与java api还是有些不同,但是它是功能完整,能够起着真正作用的java 程序。
|
|