使用 java 8 foreach 循环调用方法和处理异常

泰哈尔

如果条件满足,我正在执行下面的代码我正在生成异常,但即使我会得到异常,我也想跳过该循环并想执行剩余代码,所以有什么办法吗?

public class Test {

    public static void main(String[] args) {

        List<String> items = new ArrayList<>();
        items.add("1");
        items.add("2");
        items.add("3");
        items.add("4");
        items.add("5");

        try {
            items.forEach(item -> getData(item));
        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    public static void getData(String item) {
        System.out.println("====getData method called" + item + "====");
        if (item.equals("1")) {
            System.out.println(1 / 0);
        }



    }

}
老脾气

try/移动catch到循环内?

    items.forEach(item -> {
        try {
            getData(item);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章