Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

e.printStackTrace(); in string

There are e.printStackTrace() method to print exceptional error, so I would like to take entire exception in String and show it by Toast.makeText()
How can i do this?
If there are more alternate idea, then please share with me or suggest me.

like image 756
Nikunj Patel Avatar asked Aug 30 '11 11:08

Nikunj Patel


People also ask

How do I get e printStackTrace as string?

Example: Convert stack trace to a string In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer. Then, we simply convert it to string using toString() method.

What is e printStackTrace () in Java?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.

Why we should not use e printStackTrace ()?

e. printStackTrace() is generally discouraged because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes. The better thing to do is to use a logging framework (logback, slf4j, java.


1 Answers

Use the following piece of code:

Writer writer = new StringWriter(); exception.printStackTrace(new PrintWriter(writer)); String s = writer.toString(); 

There used to be a way to extract an exception stacktrace into the String in one line with Log.getStackTraceString call. But starting from Android 4.0 (API 14) that method is not reliable anymore, as it returns an empty string for UnknownHostException (see Android issue #21436 for the details, in short: "to reduce the amount of log spew that apps do in the non-error condition of the network being unavailable" Android engineers made IMHO a dubious decision to modify Log.getStackTraceString method).

Thus it is better to use the code I provided at the beginning of this post.

like image 126
Idolon Avatar answered Sep 19 '22 08:09

Idolon