堆栈跟踪为字符串

时间:2013-08-31 09:58:12

标签: java exception

如何在Java中获得完整的异常消息?

我正在创建一个Java应用程序。如果存在运行时异常,则会弹出JDialog JTextArea。我试图在我的应用程序中生成运行时异常,但显示异常消息的文本区域如下所示:

java.lang.ClassNotFoundException: com.app.Application

但是,我希望我的文本区域显示如下:

enter image description here

以下是我的代码的一部分,其中包含trycatch

String ex = e.toString();
this.addText(ex);

我尝试使用e.getLocalizedMessage()e.getMessage(),但这些都不起作用。

7 个答案:

答案 0 :(得分:80)

您需要拨打Throwable#printStackTrace(PrintWriter);

try{

}catch(Exception ex){
    String message = getStackTrace(ex);
}

public static String getStackTrace(final Throwable throwable) {
     final StringWriter sw = new StringWriter();
     final PrintWriter pw = new PrintWriter(sw, true);
     throwable.printStackTrace(pw);
     return sw.getBuffer().toString();
}

你也可以使用commons-lang-2.2.jar Apache Commons Lang库来提供这个功能:

public static String getStackTrace(Throwable throwable)
Gets the stack trace from a Throwable as a String.

ExceptionUtils#getStackTrace()

答案 1 :(得分:5)

如果您没有使用任何记录器(Log4j或oracle logger api),那么您可以使用以下语句打印完整的异常消息

try{
       // statement which you want to monitor 

}catch(Exception e){
    e.printStackTrace()
    // OR System.err.println(e.getStackTrace());
    // OR System.err.println(e);
    // OR System.err.println(e.getMessage());
    // OR System.err.println(e.getCause());
}

如果您使用的是Logger API,请使用以下语句

try{

         // statement which you want to monitor 

}catch(Exception e){
  log.error(e,e); 
}

答案 2 :(得分:5)

要将堆栈跟踪转换为字符串,您可以使用以下行:

    CharArrayWriter cw = new CharArrayWriter();
    PrintWriter w = new PrintWriter(cw);
    e.printStackTrace(w);
    w.close();
    String trace = cw.toString();

答案 3 :(得分:2)

e.printStackTrace将提供完整的堆栈跟踪

答案 4 :(得分:1)

尝试e.printStackTrace(),它将使用提到的行

打印您的异常的跟踪

答案 5 :(得分:1)

这是完整的异常消息。

如果您想了解更多信息,请尝试使用e.printStackTrace()

那么你会得到你在你提出的图片上看到的内容。

答案 6 :(得分:1)

public static String getStackMsg(Throwable e) {
    StringBuffer sb = new StringBuffer();
    sb.append(e.toString()).append("\n");
    StackTraceElement[] stackArray = e.getStackTrace();

    for(int i = 0; i < stackArray.length; ++i) {
        StackTraceElement element = stackArray[i];
        sb.append(element.toString() + "\n");
    }

    return sb.toString();
}