2

我想跟踪我的 Android 项目中的所有类型的异常,避免从每个 catch 块中手动收集异常。

android有没有这样的全局接口可以捕获应用程序的每个异常信息?我想在一行中跟踪每个异常。

4

3 回答 3

-1

android是否有任何这样的全局接口来捕获应用程序的每个异常的信息,以便我可以在一行中跟踪每个异常?

不,那里没有。

异常被选中或未选中。try-catch您“必须”使用or来捕获已检查的异常,throws除非代码无法编译。

任何未捕获的异常都在unCoughtExceptionHandler异常发生的线程对象中处理。

于 2015-12-11T11:39:58.757 回答
-1

如果您对应用程序在每次异常时都崩溃感到满意,您可以为当前线程上的未捕获异常设置一个处理程序,如下所示:

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

如果您在应用程序中使用 AsyncTasks 或其他线程方法,则必须在每个新线程上执行此操作。

这种方法通常用于编写自己的错误报告,也许它不是你想要做的。

如果您不希望您的应用程序崩溃,我认为您必须自己实现一些可以从 catch 块中轻松调用的东西。

于 2015-12-11T11:28:14.220 回答
-1

Not that I know of. If there was though, I'm sure no one would be using try catch blocks, and it would be a well known process/method. You can, though, debug with android studio.

Only thing I can think of that is similar could be setting a common handler to catch exceptions:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

And the method that goes with that annonymous inner class is:

        public void uncaughtException(Thread thread, Throwable throwable) {

Where you put your exceptions. I found an example on tutorialspoint.com, and edited a screen shot to make it clearer:

enter image description here

Then, you can notice that we purposely throw that runTimeException after starting the thread. So, result will be:

 Thread[Thread-0,5,main] throws exception: java.lang.RuntimeException
于 2015-12-11T11:31:05.193 回答