抛出异常而不导致应用程序崩溃

The*_*ted 6 java android exception crash-reports

我在我的 Android 项目中使用崩溃报告库。一旦激活,它会对每个未捕获的异常做出反应,并在应用程序关闭之前创建报告。

到目前为止一切顺利,但我想为此添加更多“控制”并为非异常创建报告。我的想法是这样定义“假”异常:

public final class NonFatalError extends RuntimeException {

    private static final long serialVersionUID = -6259026017799110412L;

    public NonFatalError(String msg) {
        super(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,当我想发送非致命错误消息并创建报告时,我将这样做:

throw new NonFatalError("Warning! A strange thing happened. I report this to the server but I let you continue the job...");
Run Code Online (Sandbox Code Playgroud)

如果从主线程调用,这显然会使应用程序崩溃。所以,我尝试将它放在后台线程上

new Thread(new Runnable() {     
    @Override
    public void run() {
        throw new NotFatalError("Warning! A strange thing happened. I report this to the server but I let you continue the job...");
    }
}).start();
Run Code Online (Sandbox Code Playgroud)

好主意吗?不。应用程序无论如何都会崩溃(但假崩溃报告会按预期发送)。还有其他方法可以实现我想要的吗?

Wes*_*den 5

你的异常永远不会被捕获,所以这就是你的应用程序崩溃的原因。

您可以这样做,从主线程捕获异常:

Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};

Thread t = new Thread(new Runnable() {     
    @Override
    public void run() {
        throw new NotFatalError("Warning! A strange thing happened. I report this to the server but I let you continue the job...");
    }
});

t.setUncaughtExceptionHandler(h);
t.start();
Run Code Online (Sandbox Code Playgroud)

但是您也可以从主线程运行代码并在那里捕获它..例如:

try
{
  throw new NonFatalError("Warning! blablabla...");
}
catch(NonFatalError e)
{
  System.out.println(e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

因为您的异常是从RuntimeException类扩展的,所以如果未在任何地方捕获异常,则默认行为是退出应用程序。因此,您应该在 Java 运行时决定退出应用程序之前捕获它。