java异常链与异常丢失

2014-11-24 08:26:48 · 作者: · 浏览: 0

1、在java的构造方法中提供了 异常链.. 也就是我们可以通过构造方法不断的将 异常串联成一个异常链...

只有 Throwable ----> Exception RuntimeException Error提供了 构造方法实现异常链的机制。。。其他异常需要通过initCause来

构造异常连..

下面一段代码就是异常连的一个简单示例...可以打印整个程序过程中出现的异常。。

public class TestT {
public static void a() throws Exception{ //抛出异常给上级处理
try {
b() ;
} catch (Exception e) {
throw new Exception(e) ;
}
}
public static void b() throws Exception{ //抛出异常给上级处理
try {
c() ;
} catch (Exception e) {
throw new Exception(e);
}
}
public static void c() throws Exception { //抛出异常给上级处理
try {
throw new NullPointerException("c 异常链中的空指针异常..") ;
} catch (NullPointerException e) {
throw new Exception(e) ;
}
}
public static void main(String[]args){
try {
a() ;
} catch (Exception e) {
e.printStackTrace();
}

}
}


2、 try catch ...finally 有个漏洞就是异常缺失.. 例如三个try catch 嵌套在一起 ..内部的2个try catch 就可以省略 catch ....直接 try finally ..

看下面代码 我们发现丢失了2个异常信息


public class MyTest {
public void open() throws Exception{
throw new Exception(){
public String toString() {
return this.getClass().getName()+"CeryImmportException";
};
} ;
}
public void close() throws Exception{

throw new Exception(){
public String toString() {

return this.getClass().getName()+"close Exception" ;
};
} ;
}
public void three() throws Exception{
throw new Exception(){
public String toString() {

return this.getClass().getName() + "three" ;
};
} ;
}
public static void main(String[]agrs){
MyTest mt=new MyTest() ;
try{
try{
try{
mt.open();
}finally
{
System.out.println("delete open");
mt.close() ;
}
}
finally{
System.out.println("delete close");
mt.three() ;

}
}catch(Exception ex){
ex.printStackTrace();
}
}
}

作者:yue7603835