2013-04-13 87 views
15

我想知道我該如何處理最後的Exception,其中包含詳細消息以及多個鏈接異常的所有詳細消息。獲取鏈式異常的詳細信息Java

例如,假設一個這樣的代碼:

try { 
    try { 
    try { 
     try { 
     //Some error here 
     } catch (Exception e) { 
     throw new Exception("FIRST EXCEPTION", e); 
     } 
    } catch (Exception e) { 
     throw new Exception("SECOND EXCEPTION", e); 
    } 
    } catch (Exception e) { 
    throw new Exception("THIRD EXCEPTION", e); 
    } 
} catch (Exception e) { 
    String allMessages = //all the messages 
    throw new Exception(allMessages, e); 
} 

我不感興趣,在充分stackTrace,但只有在消息我寫的。我的意思是,我想有這樣的結果:

java.lang.Exception: THIRD EXCEPTION + SECOND EXCEPTION + FIRST EXCEPTION 

回答

22

我想你需要的是:

public static List<String> getExceptionMessageChain(Throwable throwable) { 
    List<String> result = new ArrayList<String>(); 
    while (throwable != null) { 
     result.add(throwable.getMessage()); 
     throwable = throwable.getCause(); 
    } 
    return result; //["THIRD EXCEPTION", "SECOND EXCEPTION", "FIRST EXCEPTION"] 
} 
+0

的最佳解決方案,感謝名單!其他建議也很好,但是這樣我的代碼就集中在一個單一的方法中,我只需要修改從哪裏拋出* final *'Exception'的方法...... – MikO

1

你就能更好地運用這種方式,隨着新Exceptionmessage()合併以前Exceptionmessage()throw荷蘭國際集團:

 } catch (Exception e) { 
      throw new Exception("FIRST EXCEPTION" + e.getMessage(), e); 
     } 
1

循環訪問異常原因並在每個異常中附加消息。

try 
    { 
     try 
     { 
      try 
      { 
       try 
       { 
        throw new RuntimeException("Message"); 
       } 
       catch (Exception e) 
       { 
        throw new Exception("FIRST EXCEPTION", e); 
       } 
      } 
      catch (Exception e) 
      { 
       throw new Exception("SECOND EXCEPTION", e); 
      } 
     } 
     catch (Exception e) 
     { 
      throw new Exception("THIRD EXCEPTION", e); 
     } 
    } 
    catch (Exception e) 
    { 
     String message = e.getMessage(); 
     Throwable inner = null; 
     Throwable root = e; 
     while ((inner = root.getCause()) != null) 
     { 
      message += " " + inner.getMessage(); 
      root = inner; 
     } 
     System.out.println(message); 
    } 

它打印

第三個例外第二個例外FIRST異常消息

1

你可以只添加先前異常消息在每個例外

這是一個例子:

public static void main(String[] args) { 

    try { 
     try { 
      try { 
       try { 
        throw new Exception(); 
        // Some error here 
       } catch (Exception e) { 
        throw new Exception("FIRST EXCEPTION", e); 
       } 
      } catch (Exception e) { 
       Exception e2 = new Exception("SECOND EXCEPTION + " + e.getMessage()); 
       throw e2; 
      } 
     } catch (Exception e) { 
      Exception e3 = new Exception("THIRD EXCEPTION + " + e.getMessage()); 
      throw e3; 
     } 
    } catch (Exception e) { 
     System.out.println(e); 
    } 
} 

結果是:java.lang.Exception的:第三個例外+第二個例外+第一個例外