在Android中用e.printStackTrace()

本文探讨了在Android应用中处理异常的最佳方式,建议避免使用printStackTrace(),转而推荐使用Android内置的日志(Log)类来记录错误信息,提供了具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

5 Answers

up vote 22 down vote accepted

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.

share improve this answer
 

I believe this is what you need:

catch (Exception e) {
     Log.e(TAG,Log.getStackTraceString(e)); 
}
share improve 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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值