不崩溃应用程序的情况下抛出异常

6
我正在我的Android项目中使用一个崩溃报告库。一旦激活,它会对每个未捕获的异常做出反应,并在应用关闭之前创建报告。
到目前为止一切都很好,但我想为非异常情况添加更多的“控制”,并创建报告。我的想法是这样定义一个“虚假”异常:
public final class NonFatalError extends RuntimeException {

    private static final long serialVersionUID = -6259026017799110412L;

    public NonFatalError(String msg) {
        super(msg);
    }
}

所以,当我想发送一个非致命错误消息并创建报告时,我会这样做:

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

如果从主线程调用,这显然会导致应用程序崩溃。因此,我尝试将其放在后台线程上!
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();

一个好主意吗?不是的。无论如何应用程序都会崩溃(但伪造的崩溃报告如预期发送)。是否有另一种实现我想要的方式?

1
//有没有其他方法可以实现我想要的?// 没有,你必须捕获异常来防止应用程序崩溃。 - samthebest
2个回答

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();

但是您也可以在主线程中运行代码并在那里捕获它。像这样:

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

由于你的异常扩展自RuntimeException类,因此如果该异常在任何地方都没有被捕获,那么默认行为就是退出应用程序。 这就是为什么你应该在Java运行时决定退出应用程序之前捕获它的原因。


这种方法不会终止应用程序,但也不会激活崩溃报告工具。 - TheUnexpected
@Wessel 我在考虑将那段代码作为一个切面,并将其编码为注解。 - Mehdi

0

1
我知道Crashlytics并且之前曾与其一起工作。现在我们需要更改一些代码库,并切换到新的Parse CrashReport库(http://blog.parse.com/2014/12/09/introducing-parse-crash-reporting-2/)。它比Craslytics简单得多,但目前还没有包含那样的功能。 - TheUnexpected

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接