java异常链与异常丢失

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

之所以需要异常连,是因为处于代码的可理解性,以及阅读和程序的可维护性... 

我们知道我们每抛出一个异常都需要进行try catch ...那么岂不是代码很臃肿...

我们如果可以将异常串联成一个异常连,然后我们只捕获我们的包装 异常,我们知道 RuntimeException 以及其派生类可以不进行try catch 而被jvm自动捕获并处理..

当然了我们可以自己定义自己的异常类从RuntimeException中派生,然后通过一级一级的包装,假如异常出现了JWM通过我们的自定义RuntimeException直接输出 cause

(原因)也就是 我们的异常链..因此我们的所有异常也就输出了,这样就减少了很多的异常处理的代码。。。

只有 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();  
  }
 } 
}

 

 

posted @ 2012-06-28 16:02  programmer小卫  阅读(186)  评论(0)    收藏  举报