首页 > 解决方案 > 在另一个线程中捕获库引发的异常(android)

问题描述

我正在使用一个库,有时(大约 100 次中的 1 次)会引发ConcurrentModificationException应用程序崩溃。

堆栈跟踪没有提到我的任何代码,而是提到了库的代码。我试图捕捉我调用库的异常,但它不起作用。

我猜这个异常是在库中的一个新线程中引发的。

我怎么能捕捉到这样的异常?

库: 旧的 Philips Hue Java 库。(我很快就要换新的了。)

例外:

E/AndroidRuntime: FATAL EXCEPTION: Thread-21319
    Process: my.package, PID: 21561
    Theme: themes:{...}
    java.util.ConcurrentModificationException
        at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
        at com.philips.lighting.hue.sdk.notification.impl.PHNotificationManagerImpl$3.onReceived(PHNotificationManagerImpl.java:180)
        at com.philips.lighting.hue.sdk.notification.impl.PHHueResultReceiver.execute(PHHueResultReceiver.java:24)
        at com.philips.lighting.hue.sdk.notification.impl.PHNotificationManagerImpl.notifyBridgeSearchResult(PHNotificationManagerImpl.java:188)
        at com.philips.lighting.hue.sdk.upnp.PHBridgeSearchManagerImpl$1.run(PHBridgeSearchManagerImpl.java:198)

标签: javaandroidexception

解决方案


我猜你在迭代时修改了数组值。

Java Collection 类是快速失败的,这意味着如果在某个线程使用迭代器遍历它时更改 Collection,iterator.next() 将抛出 ConcurrentModificationException。

以下是如何避免它: How to Avoid java.util.ConcurrentModificationException when iterate through and remove elements from an ArrayList


推荐阅读