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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With