简体   繁体   English

Java捕获异常并继续执行

[英]java catching exception and continue execution

I want to catch an exception, print the place the exception occured and continue running the loop. 我想捕获一个异常,打印发生异常的地方并继续运行循环。 I have this example code: 我有以下示例代码:

public class justcheckin {
static String[] l = {"a","a","b","a","a"};

public class notAexception extends Exception{

    private static final long serialVersionUID = 1L;

    notAexception (){
        super();
    }
    notAexception(String message){
        super(message);
    }
}

private  void loop () throws notAexception {
    notAexception b = new notAexception("not an a");
    for (int i = 0; i< l.length; i++){
        if (! l[i].equals("a")){
            throw b;
        }
    }
}

public static void main (String[] args) throws notAexception{
    justcheckin a = new justcheckin();
    a.loop();
}
  }

I want to write a warning message, say "index 2 is not a", and continue running the loop. 我想写一条警告消息,说“索引2不是a”,然后继续运行循环。 How can I do it? 我该怎么做?

Thanks! 谢谢!

I think in your code there is no need to have try catch throw etc. 我认为在您的代码中,无需尝试捕获抛出等。

But still in your same code if you want to perform this, 但是如果您要执行此操作,仍使用相同的代码,

    public class justcheckin {
static String[] l = {"a","a","b","a","a"};

public class notAexception extends Exception{

    private static final long serialVersionUID = 1L;

    notAexception (){
        super();
    }
    notAexception(String message){
        super(message);
    }
}

private  void loop () throws notAexception {
    notAexception b = new notAexception("not an a");
    for (int i = 0; i< l.length; i++){
        try{
            if (! l[i].equals("a")){
                throw b;
            }
        }catch(notAexception ne){
            System.out.println("index "+i+" is not a");//index 2 is not a
        }
    }
}

public static void main (String[] args) throws notAexception{
    justcheckin a = new justcheckin();
    a.loop();
}
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM