堆栈跟踪为字符串

Jer*_*emy 34 java exception

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

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

java.lang.ClassNotFoundException: com.app.Application
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

这是我的代码的一部分被try和包围catch:

String ex = e.toString();
this.addText(ex);
Run Code Online (Sandbox Code Playgroud)

我试着用e.getLocalizedMessage()e.getMessage(),但这些都不能工作.

Nar*_*hai 82

你需要打电话给 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();
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用commons-lang-2.2.jar Apache Commons Lang库来提供此功能:

public static String getStackTrace(Throwable throwable)
Gets the stack trace from a Throwable as a String.
Run Code Online (Sandbox Code Playgroud)

ExceptionUtils#的getStackTrace()


Rak*_*oni 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());
}
Run Code Online (Sandbox Code Playgroud)

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

try{

         // statement which you want to monitor 

}catch(Exception e){
  log.error(e,e); 
}
Run Code Online (Sandbox Code Playgroud)


Hen*_*nry 5

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

    CharArrayWriter cw = new CharArrayWriter();
    PrintWriter w = new PrintWriter(cw);
    e.printStackTrace(w);
    w.close();
    String trace = cw.toString();
Run Code Online (Sandbox Code Playgroud)