0

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!

3
  • 1
    just remove the throw b; section and instead write a Logger message. Commented May 21, 2014 at 4:53
  • 2
    there is no try catch in your code, how it will catch then? Commented May 21, 2014 at 4:54
  • Class names Should Start with capital Letter , ie camelcase Commented May 21, 2014 at 5:22

1 Answer 1

3

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();
}
  }
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot! it works. Another newbie question: what is the meaning of "ne" in the 'catchw phrase?
'ne' is just a variable. Just like you took 'justcheckin a'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.