如何在不中断Java中的for循环的情况下引发异常?
每当循环中发生异常时,控件就会通过处理异常而退出循环,方法中catch块之后的语句将被执行。但是,循环中断了。
示例
public class ExceptionInLoop{
public static void sampleMethod(){
String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"};
try {
for(int i=0; i<=10; i++) {
System.out.println(str[i]);
System.out.println(i);
}
}catch (ArrayIndexOutOfBoundsException ex){
System.out.println("Exception occurred");
}
System.out.println("hello");
}
public static void main(String args[]) {
sampleMethod();
}
}输出结果
Mango 0 Apple 1 Banana 2 Grapes 3 Oranges 4 Exception occurred Hello
执行循环而不中断的一种方法是将导致异常的代码移到另一个处理该异常的方法。
如果您在循环中有trycatch,则无论异常如何,它都会完全执行。
示例
public class ExceptionInLoop{
public static void print(String str) {
System.out.println(str);
}
public static void sampleMethod()throws ArrayIndexOutOfBoundsException {
String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"};
for(int i=0; i<=10; i++) {
try {
print(str[i]);
System.out.println(i);
} catch(Exception e){
System.out.println(i);
}
}
}
public static void main(String args[]) {
try{
sampleMethod();
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("");
}
}
}输出结果
Mango 0 Apple 1 Banana 2 Grapes 3 Oranges 4 5 6 7 8 9 10
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志