我在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();
一个好主意?不会。应用程序无论如何都会崩溃(但是假的崩溃报告会按预期发送)。还有另一种方法可以达到我的目的吗?
答案 0 :(得分:2)
您的异常永远不会被捕获,因此这就是您的应用程序崩溃的原因。
你可以这样做从主线程中捕获异常:
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 Runtime决定退出应用程序之前捕获它。
答案 1 :(得分:0)
您正在使用例外来创建日志。你不应该这样做。如果您使用的是像crashlytics(https://try.crashlytics.com/)这样的库,您可以发送此链接中的日志报告:http://support.crashlytics.com/knowledgebase/articles/120066-how-do-i-use-logging
您正在使用的库应该使用类似的方法。
如果您想继续使用Exceptions,则需要捕获它们以免崩溃应用程序。