Reputation: 21
i would like to know how an error can be caught in java but allow the program to continue to run.
here is my example:
public class test1 {
public static void main(String[] args) {
String str = new String("abcdefghij");
try {
System.out.println(str.charAt(0));
System.out.println(str.charAt(9));
System.out.println(str.charAt(10));
System.out.println("is it still running");
} catch (Exception e) {
System.out.println("the index is out of bounds");
}
}
}
the following is printed:
a
j
the index is out of bounds
but after the error is thrown i would like the code to continue to run so that this is printed:
a
j
the index is out of bounds
is it still running
thanks in advance
Upvotes: 2
Views: 687
Reputation:
Java does not support 'resuming' or 'restarting' after an exception.
You can wrap the specific line "to skip" in a try/catch
(would be 3 total in the above example, one for each access) or, perhaps better, write code that will not throw an exception -- exceptions really ought to be "exceptional" IMOHO. You could also move the try/catch
code into a method to "wrap" the access (e.g. call the method 3x), but the actions are the same.
Upvotes: 7
Reputation: 764
for(int i =0; i < Short.MAX_VALUE; i++){
try{
System.out.println(str.charAt(i));
}catch(Exception ex){}
}
Also you can use finally bolck if you wish to execute always.
Upvotes: 2