How to continue executing a java program after an Exception is thrown?
Move the try catch block within for loop and then it should work
You need to re-structure it slightly, so that the try/catch is inside the for loop, not enclosing it, e.g.
for (...) {
try {
// stuff that might throw
}
catch (...) {
// handle exception
}
}
As an aside, you should avoid using exceptions for flow control like that - exceptions should be used for exceptional things.
Your code should look as follows:
public class ExceptionsDemo {
public static void main(String[] args) {
for (int i=args.length;i<10;i++){
try {
if(i%2==0){
System.out.println("i =" + i);
throw new Exception(); // stuff that might throw
}
} catch (Exception e) {
System.err.println("An exception was thrown");
}
}
}
}