堆栈跟踪作为字符串 [英] Stack trace as String

查看:174
本文介绍了堆栈跟踪作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  java.lang .ClassNotFoundException:com.app.Application 

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



这里是我的代码的一部分,由 try catch / p>

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

我试图使用 e.getLocalizedMessage() e.getMessage(),但这两者都不起作用。

解决方案

您需要调用 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)
从Throwable获取堆栈跟踪作为字符串。

ExceptionUtils#getStackTrace()


How do I get full exception message in Java?

I am creating a Java Application. If there is a runtime exception, a JDialog with a JTextArea will pop up. I tried to make a runtime exception in my application, but the text area showing the exception message looks like this:

java.lang.ClassNotFoundException: com.app.Application

However, I want my text area to show something like:

Here is some part of my code surrounded by the try and catch:

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

I've tried to use e.getLocalizedMessage() and e.getMessage(), but neither of these work.

解决方案

You need to call the 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();
}

You can also use commons-lang-2.2.jar Apache Commons Lang library which provides this functionality:

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

ExceptionUtils#getStackTrace()

这篇关于堆栈跟踪作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆