java捕获异常并继续执行

时间:2014-05-21 04:51:58

标签: java loops exception throw

我想捕获异常,打印出现异常的地方并继续运行循环。我有这个示例代码:

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();
}
  }

我想写一条警告信息,说“索引2不是”,然后继续运行循环。 我该怎么办?

谢谢!

1 个答案:

答案 0 :(得分:3)

我认为在你的代码中没有必要尝试catch throw等。

但如果你想执行此操作,仍然使用相同的代码,

    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();
}
  }