zoukankan      html  css  js  c++  java
  • java的for循环中遇到异常抛出后继续循环执行

    @Test
    public void loopTryCatchTest() throws Exception {

    Map<String, Object> a = new HashMap();
    a.put("a", "1");
    a.put("b", null);
    a.put("c", "3");


    for (Map.Entry<String, Object> moEntry : a.entrySet()) {
    try{
    boolean flag = moEntry.getValue().equals("1");
    System.out.println(moEntry.getKey() + "," + moEntry.getValue() + "," + flag);

    } catch(Exception e){
    System.out.println("异常跳出" + e);
          //continue;--- 不需要写continue,因为写不写,都会继续循环,不会异常后直接退出的。
    }
    }

    }


    执行结果:

    a,1,true
    异常跳出java.lang.NullPointerException
    c,3,false

    如果try包在for循环外面,则无法达到预期效果,遇到异常抛出,被catch住后,循环无法继续执行。

    @Test
    public void loopTryCatchTest() throws Exception {

    Map<String, Object> a = new HashMap();
    a.put("a", "1");
    a.put("b", null);
    a.put("c", "3");

    try {
    for (Map.Entry<String, Object> moEntry : a.entrySet()) {

    boolean flag = moEntry.getValue().equals("1");
    System.out.println(moEntry.getKey() + "," + moEntry.getValue() + "," + flag);


    }
    }catch (Exception e) {
      System.out.println("异常跳出" + e);
      }

    }
  • 相关阅读:
    Linux删除文件相关命令
    Bing语句
    VS2013配置Winpcap
    node10-mongoose
    node09-cookie
    node08-express
    node07-http
    node06-path
    node05-fs
    node04-buffer
  • 原文地址:https://www.cnblogs.com/zaierzai/p/12447265.html
Copyright © 2011-2022 走看看