android – 记录它后的Rethrow UncaughtExceptionHandler异常

前端之家收集整理的这篇文章主要介绍了android – 记录它后的Rethrow UncaughtExceptionHandler异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的Application类中,我试图在它发生之前捕获一个强制关闭,所以我可以记录它然后重新抛出它以便 android可以处理它.我这样做是因为有些用户没有报告强制关闭.

我在eclipse中开发,eclipse不允许我重新抛出异常.它显示错误说“未处理的异常类型Throwable:Surround with try / catch”.我怎样才能重新抛出异常?

public class MainApplication extends Application
{
    @Override
    public void onCreate()
    {
    super.onCreate();

    try
    {
        //Log exception before app force closes
        Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread,Throwable ex) {
                AnalyticsUtils.getInstance(MainApplication.this).trackEvent(
                        "Errors",// Category
                        "MainActivity",// Action
                        "Force Close: "+ex.toString(),// Label
                        0);                             // Value
                AnalyticsUtils.getInstance(MainApplication.this).dispatch();

                Toast.makeText(MainApplication.this,"Snap! Something broke. Please report the Force Close so I can fix it.",Toast.LENGTH_LONG);

                //rethrow the Exception so user can report it
                //throw ex; //<-- **eclipse is showing an error to surround with try/catch**
            }
        });

    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

}

解决方法

道歉,而不是Android专家 – 但看起来你不能抛出ex,因为你的方法签名“void uncaughtException(Thread,Throwable)”并没有声明它“抛出”任何东西.

假设您正在覆盖API接口并且(a)无法修改此签名并且(b)不想因为您将其抛弃在上下文之外,您是否可以使用装饰器模式并基本上将默认子类化UncaughtExceptionHandler实现记录您的消息,然后让它像往常一样进行处理?

编辑:未经测试,但这看起来有点像:

final UncaughtExceptionHandler subclass = Thread.currentThread().getUncaughtExceptionHandler();
    Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread,Throwable ex) {
            // your code 
            AnalyticsUtils.getInstance(MainApplication.this).trackEvent(
                    "Errors",// Category
                    "MainActivity",// Action
                    "Force Close: "+ex.toString(),// Label
                    0);                             // Value
            AnalyticsUtils.getInstance(MainApplication.this).dispatch();
            Toast.makeText(MainApplication.this,Toast.LENGTH_LONG).show();

            // carry on with prior flow
            subclass.uncaughtException(thread,ex);
        }
    });
原文链接:https://www.f2er.com/android/311280.html

猜你在找的Android相关文章