Android try / catch无效

时间:2015-10-01 14:06:07

标签: java android try-catch

我的Android应用中有系统用于发送有关未捕获异常的报告(Google Play帐户不属于我)。几天前我遇到了以下错误:

java.util.ConcurrentModificationException
java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
onlineorganizer.Adapter.fillGrid(Adapter.java:332)
onlineorganizer.Adapter.access$6(Adapter.java:314)
onlineorganizer.Adapter$1.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阻止没有捕获异常?

2 个答案:

答案 0 :(得分:1)

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

参见例如:

TryCatch ConcurrentModificationException catching `30% of the time

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

答案 1 :(得分:0)

你的情况:
if (iter.hasNext())
是没有尝试阻止把它放在try块中然后检查它。希望它会帮助你:)