记录它后Rethrow UncaughtExceptionHandler异常

Rya*_*n R 6 eclipse android exception-handling exception

在我的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Cap*_*row 13

道歉,而不是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, "Snap! Something broke. Please report the Force Close so I can fix it.", Toast.LENGTH_LONG).show();

            // carry on with prior flow
            subclass.uncaughtException(thread, ex);
        }
    });
Run Code Online (Sandbox Code Playgroud)