如何在不跳出 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
不中断循环执行的一种方法是将导致异常的代码移到另一个处理异常的方法中。
如果在循环中使用 try-catch,则尽管发生异常,该循环仍将得到完整执行。
示例
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
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP