java異常鏈與異常丟失 – JAVA編程語言程序開發技術文章

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

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *