【问题标题】:Throw an Exception without crashing the app抛出异常而不使应用程序崩溃
【发布时间】:2014-12-19 14:45:28
【问题描述】:

我在我的 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();

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

【问题讨论】:

  • //还有其他方法可以实现我想要的吗?//不,您必须捕获异常以阻止它使应用程序崩溃。

标签: java android exception crash-reports


【解决方案1】:

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

你可以这样做从你的主线程捕获异常:

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 运行时决定退出应用程序之前捕获它。

【讨论】:

  • 此方法不会杀死应用程序,但也不会激活崩溃报告工具。
  • @Wessel 我正在考虑使该代码成为一个方面并将其编码到注释中〜
【解决方案2】:

您正在使用异常来创建日志。你不应该那样做。如果您使用的是 crashlytics (https://try.crashlytics.com/) 之类的库,您可以在此链接中发送日志报告:http://support.crashlytics.com/knowledgebase/articles/120066-how-do-i-use-logging

您使用的库应该有类似的方法。

如果您想继续使用异常,您需要捕获它们以免应用程序崩溃。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
相关资源
最近更新 更多