242

How can I get the e.printStackTrace() and store it into a String variable? I want to use the string generated by e.printStackTrace() later in my program.

I'm still new to Java so I'm not too familiar with StringWriter that I think will be the solution. Or if you have any other ideas please let me know. Thanks

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
ace
  • 6,775
  • 7
  • 38
  • 47
  • 1
    Not actually the same question: the other question actually specifies that they just want to convert the result of `Throwable.getStackTrace()` to a string. That could contain quite a bit less information than would be shown by `Throwable.printStackTrace`. – SamB Feb 05 '20 at 01:56

8 Answers8

495

Something along the lines of

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();

Ought to be what you need.

Relevant documentation:

shanet
  • 7,246
  • 3
  • 34
  • 46
Zach L
  • 16,072
  • 4
  • 38
  • 39
  • 1
    @Zach L - Thanks for your answer. it worked for me to print the stack trace along with personalized(Customized) error message. Thanks again for your help. – Umamaheshwar Thota Mar 07 '13 at 10:47
  • 3
    This prints the nested causes of the thrown exception too which is just what I needed. Thanks! – Tim Stewart Sep 27 '13 at 20:00
  • 4
    what about closing `PrintWriter` after usage to release resources? Reading the docs I found that is not necessary for StringWriter. – jelies Jan 22 '14 at 09:29
78

Guava makes this easy with Throwables.getStackTraceAsString(Throwable):

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);

Internally, this does what @Zach L suggests.

lakshayg
  • 2,053
  • 2
  • 20
  • 34
ColinD
  • 108,630
  • 30
  • 201
  • 202
20

You can use the ExceptionUtils.getStackTrace(Throwable t); from Apache Commons 3 class org.apache.commons.lang3.exception.ExceptionUtils.

http://commons.apache.org/proper/commons-lang/

ExceptionUtils.getStackTrace(Throwable t)

Code example:

try {

  // your code here

} catch(Exception e) {
  String s = ExceptionUtils.getStackTrace(e);
}
thiagoh
  • 7,098
  • 8
  • 51
  • 77
16

You have to use getStackTrace () method instead of printStackTrace(). Here is a good example:

import java.io.*;

/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {

  public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
  }

  /**
  * Defines a custom format for the stack trace as String.
  */
  public static String getCustomStackTrace(Throwable aThrowable) {
    //add the class name and any message passed to constructor
    final StringBuilder result = new StringBuilder( "BOO-BOO: " );
    result.append(aThrowable.toString());
    final String NEW_LINE = System.getProperty("line.separator");
    result.append(NEW_LINE);

    //add each element of the stack trace
    for (StackTraceElement element : aThrowable.getStackTrace() ){
      result.append( element );
      result.append( NEW_LINE );
    }
    return result.toString();
  }

  /** Demonstrate output.  */
  public static void main (String... aArguments){
    final Throwable throwable = new IllegalArgumentException("Blah");
    System.out.println( getStackTrace(throwable) );
    System.out.println( getCustomStackTrace(throwable) );
  }
} 
14

Along the lines of Guava, Apache Commons Lang has ExceptionUtils.getFullStackTrace in org.apache.commons.lang.exception. From a prior answer on StackOverflow.

Community
  • 1
  • 1
Mihai Danila
  • 2,229
  • 1
  • 23
  • 28
7
StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}
Jonathon Faust
  • 12,396
  • 4
  • 50
  • 63
2

Use the apache commons-lang3 lib

import org.apache.commons.lang3.exception.ExceptionUtils;

//...

String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
logger.error(StringUtils.join(ss, System.lineSeparator()));
lakshayg
  • 2,053
  • 2
  • 20
  • 34
Eric
  • 22,183
  • 20
  • 145
  • 196
1
call:  getStackTraceAsString(sqlEx)

public String getStackTraceAsString(Exception exc)  
{  
String stackTrace = "*** Error in getStackTraceAsString()";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
    stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
    } 
catch( UnsupportedEncodingException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
ps.close();
try {
    baos.close();
    } 
catch( IOException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
return stackTrace;
}
David Starkey
  • 1,840
  • 3
  • 32
  • 48
Stan Towianski
  • 411
  • 2
  • 6