2013-04-13 39 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的:第三个例外+第二个例外+第一个例外