How to save JAVA Exception printStackTrace on String
Probably you've used sometines the Exception object in try/catch block to print the exception stack trace that help us to find where the line of code where the exception is thrown, but more than once i wanted to get that stack trace in some String variable for example, maybe to save in some auditory table or something like that. I read a little bit about the method getStackTrace but really it doesn't give me the full stack trace.
Well, to do that, first you have to understand that when you call ex.printStackTrace() you print a characters stream on screen, so the way to get that characters stream is using the overloaded version of printStackTrace(PrintWriter objWriter) that receives a PrintWriter object to transfer that characters stream to the PrintWriter object, then you can use that writer to "write" it's stream on something like a file or a simple String.
Check this sample code:
import java.io.File;
import java.io.IOException;
class MyClass {
public static void main(String[] arguments)
{
try
{
(new MyClass()).readInexistentFile();
}
catch(IOException ex)
{
//Catch the stack trace?
}
}
public void readInexistentFile() throws IOException
{
File myFile = new File("hi6.txt");
FileReader myReader = new FileReader(myFile);
myReader.read();
}
}
...







