Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack trace as String

Tags:

java

exception

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:

enter image description here

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.

like image 921
Jeremy Avatar asked Aug 31 '13 09:08

Jeremy


Video Answer


1 Answers

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()

like image 139
Narendra Pathai Avatar answered Oct 03 '22 04:10

Narendra Pathai