We help IT Professionals succeed at work.

Capture e.printStackTrace in a string

afpcos
afpcos asked
on
Medium Priority
1,101 Views
Last Modified: 2008-03-06
I have a class that sends e-mail.  I want to be able to send an exceptions printStackTrace() in the message of the e-mail.

Can anyone tell me how I can capture this in a string?

Thanks!!
Comment
Watch Question

Commented:
The Throwable class defines additional printStackTrace methods:

public void printStackTrace(PrintStream s);

and for 1.1:

public void printStackTrace(PrintWriter s);

PrintStream (and PrintWriter) take an OutputStream in their constructors. If you feed it a ByteArrayOutputStream, you can then, after the printStackTrace is done, call toString on the ByteArrayOutputStream and it will give you your string.
import java.io.*;
class Test
{
public static void main(String args[]) throws Exception
{
try
{
throw new Exception();
}
catch(Exception e)
{
ByteArrayOutputStream file = new ByteArrayOutputStream();
PrintStream stream = new PrintStream(file);
e.printStackTrace(stream);
System.out.println("The result is :"+file.toString().trim());
}
}
}

Hope this hepls you out.

Siddharth


Explore More ContentExplore courses, solutions, and other research materials related to this topic.