Android try/catch 无效

Android try/catch didn't work

我的 Android 应用程序中有一个系统可以发送有关未捕获异常的报告(google 游戏帐户不属于我)。几天前我遇到了以下错误:

java.util.ConcurrentModificationException
java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
onlineorganizer.Adapter.fillGrid(Adapter.java:332)
onlineorganizer.Adapter.access(Adapter.java:314)
onlineorganizer.Adapter.run(Adapter.java:131)
java.lang.Thread.run(Thread.java:856)

它出现在以下方法中:

private void fillGrid(GridLayout layout) {
    grid = layout;
    Iterator<View> iter = null;
    boolean isCellsEmpty;
    if(cells == null) {
        cells = new LinkedList<View>();
        isCellsEmpty = true;
    } else {
        iter = cells.iterator();
        isCellsEmpty = false;
    }
    if(dates != null) {
        for (final String date : dates) {
            JSONObject event = events.get(date);
            View view;
            if(isCellsEmpty) {
                view = null;
            } else {
                if (iter.hasNext())
                    try {
                        // HERE
                        view = iter.next(); //exception appears HERE
                        // HERE
                    }
                    catch (ConcurrentModificationException e) {
                        Log.e("next in list", e.toString());
                        return;
                    }
                else
                    view = null;
            }
            if (event!=null && event.has("evid")) {
                view = getEventView(date, view);
            } else {
                view = getEmptyView(date, view);
            }
            if(isCellsEmpty && cells != null) {
                cells.add(view);
            }
        }
    }
}

如您所见,异常出现在 try/catch 块中,应该可以处理它。现在你可以猜到我有什么问题了。

为什么 catch 块没有捕获异常?

您的情况:
if (iter.hasNext())
超出 try 块将其放入 try 块然后检查它。希望它能帮助您 :)

您需要排除问题发生的原因。您可以同步访问数据结构或使用线程安全数据结构。

参见示例:

TryCatch ConcurrentModificationException catching `30% of the time

http://nerddawg.blogspot.hk/2004/09/concurrent-modification-of-collections.html