UncaughtExceptionHandler概率

时间:2011-08-04 10:47:42

标签: java android multithreading

我有一个班级(在它自己的文件中)

public class UncaughtExceptionHandler implements 

 java.lang.Thread.UncaughtExceptionHandler

在我的主程序中,我有以下内容: -

Thread.setDefaultUncaughtExceptionHandler( new UncaughtExceptionHandler());

编译时出现以下错误: -

cannot instantiate the type Thread.UncaughtExceptionHandler

我在这里错过了一些基本观点吗?

这是代码:     import java.io。*;

导入android.content。*;

公共类UncaughtExceptionHandler实现         java.lang.Thread.UncaughtExceptionHandler {     private final Context myContext;

public UncaughtExceptionHandler(Context context) {
    myContext = context;
}

public void uncaughtException(Thread thread, Throwable exception) {
        boolean crashedOnLastClose = false;
    MyApplication.writeProgressLog("before isfinishing".ERROR_FILE_NAME);
    // The application is being destroyed by the O/S
        crashedOnLastClose = true;

        MyApplication.writeProgressLog("after isfinishing",ERROR_FILE_NAME);


    }   


}

3 个答案:

答案 0 :(得分:2)

<强>问题

声明

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler());

new UncaughtExceptionHandler()

实际上是

new java.lang.Thread.UncaughtExceptionHandler()

这是抛出异常

<强>解

检查文件UncaughtExceptionHandler.java

找到包:(文件顶部的

package your.package;

现在转到您的主程序

替换

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler()); 

Thread.setDefaultUncaughtExceptionHandler(new your.package.UncaughtExceptionHandler()); 

答案 1 :(得分:0)

UncaughtExceptionHandler是一个接口,无法实例化接口。你需要实现它的方法。

您的代码应如下所示:

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // your code
    }
});

希望这有帮助。

答案 2 :(得分:0)

我的IDE在使用@Override的同一构造中遇到了类似的问题。 新类型Thread.UncaughtExceptionHandler(){}的方法uncaughtException(Thread,Throwable)必须覆盖超类方法:

        Thread.UncaughtExceptionHandler uce = new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                String s = "ssh to user@" + host + " failed";
                log.error(s);
                throw new IllegalStateException(s, e);
            }
        };
相关问题