在Android中用e.printStackTrace()

来源:互联网 发布:多益网络加班 编辑:程序博客网 时间:2024/05/09 01:27

Is it a bad idea to use printStackTrace() in Android Exceptions?

up vote35down votefavorite
7

Is it a bad idea to use printStackTrace() in Android Exceptions like this?

} catch (Exception e) {    e.printStackTrace();}
shareimprove this question
 

5 Answers

activeoldestvotes
up vote22down voteaccepted

Yes, it is a bad idea. You should instead use Android's built-in log class specifically designed for these purposes: http://developer.android.com/reference/android/util/Log.html

It gives you options to log debug messages, warnings, errors etc.

shareimprove this answer
 
up vote26down vote

I believe this is what you need:

catch (Exception e) {     Log.e(TAG,Log.getStackTraceString(e)); }
shareimprove this answer
 
23 
Nope. What the OP needs is Log.e(TAG, "Explanation of what was being attempted when the exception was thrown", e). Note the third parameter. Log.e(String,String,Throwable) gets the stacktrace string from the Throwable for you. Use the message parameter for something meaningful. – spaaarky21 Jun 20 '14 at 23:27 
 
@spaaarky21 You should make that an answer. – AndreKR May 5 '16 at 3:22
 
@AndreKR Someone already did. :) And I upvoted it. I just wanted to point out that this answer is promoting a bad practice, since it's rated so highly compared to correct answers. – spaaarky21 May 5 '16 at 16:54
 
@spaaarky21 I learned from your answer that I can pass an Exception to android.util.Log.e(). I didn't learn that from any of the other answers. (I didn't click the link in Nailuj's answer.) – AndreKR May 5 '16 at 16:56
 
@AndreKR Thanks. And good point. I was referring to Ryan's answer but now that I look again, I see that it's using Log in an unusual way – using a Log instance (I assume?) and passing the level in as a parameter. I added an answer. – spaaarky21 May 5 '16 at 18:09 
0 0
原创粉丝点击