本文介绍了e.printStackTrace();字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

e.printStackTrace()方法来打印特殊的错误,所以我想将整个异常字符串,并显示通过 Toast.makeText()
我怎样才能做到这一点?
如果有更多的替代想法,那么请与我分享或暗示我。

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.

推荐答案

使用下面这段code:

Use the following piece of code:

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

 

 

更新(过时,见下文)

正如他的回答指出通过@BlackRider有一种方法来提取异常堆栈跟踪到的字符串(,但在Android 4.x的它并不总是可靠的,检查更新2以下的):

As pointed by @BlackRider in his answer there is a way to extract an exception stacktrace into the String (but on Android 4.x it's not always reliable, check Update 2 below):

String stackTrace = Log.getStackTraceString(exception);

更新2

不过从Android 4.0的(API 14)开始, Log.getStackTraceString 方法是不可靠的了,因为的为的UnknownHostException (见的Andr​​oid 问题#21436 了解细节,简而言之就是:减少量日志喷出的应用程序在做网络正在恕我直言,一个可疑的决定,修改 Log.getStackTraceString 法)不可用的Andr​​oid工程师的非错误状态。
因此,它仍然是最好使用code我提供在这篇文章的开头。

But starting from Android 4.0 (API 14) Log.getStackTraceString 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's still better to use the code I provided at the beginning of this post.

这篇关于e.printStackTrace();字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 19:54