使用setDefaultUncaughtExceptionHandler进行程序的异常捕获

      对于android程序,当我们不方便链接设备进行查看log输出,或者其他原因无法直接查看的情况,我们就可以采用把错误log记录在本地,然后发送到我们的服务器的方式来获取log信息。


      那么,我们就会使用到这个方法

public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
     defaultUncaughtExceptionHandler = eh;
 }
      这是Thread类的一个静态方法,作用就是

Set the default handler invoked when a thread abruptly terminates
* due to an uncaught exception, and no other handler has been defined
* for that thread.
      也就是相当于,在全局做了一个catch处理,对于那些没有被捕获的异常进行捕获,我们需要做的就是定义一个

UncaughtExceptionHandler然后通过setDefaultUncaughtExceptionHandler设置进去就可以。

private class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
    //Throwable  代表发生异常
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        ex.printStackTrace();
       //  通过流写到一个文件
        //ex.printStackTrace(err)
        FileUtils.string2File(getErrorInfo(ex), FileUtils.LOGPATH);
        android.os.Process.killProcess(android.os.Process.myPid());
       //杀死当前自己进程
} /** * 获取错误的信息 * * @param arg1 * @return */ private String getErrorInfo(Throwable arg1) { Writer writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); arg1.printStackTrace(pw); pw.close(); String error = writer.toString(); return error; }}
       然后就能找到我们的log日志在路径 LOGPATH

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值