Search code examples
javaloopsexceptionthrow

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. How can I do it?

Thanks!


Solution

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