我有一个程序可以运行并捕获错误,但是我希望它完成循环并且在捕获错误时不会停止。
public class myClass {
int[] table;
int size;
public myClass(int size) {
this.size = size;
table = new int[size];
}
public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
myClass testInst;
try {
for (int i = 0; i < 6; i++) {
testInst = new myClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
}catch (NegativeArraySizeException e) {
System.out.println("Must not be a negative.");
}
}
}
错误发生在数组大小为负数时,但我该如何继续完成循环?
最佳答案
但是我希望让它完成循环并且在捕获到错误时不停止。
好的。然后将 try
和 catch
移到循环中。
for (int i = 0; i < 6; i++) {
try {
testInst = new myClass(sizes[i]);
System.out.println("New example size " + testInst.size);
} catch (NegativeArraySizeException e) {
System.out.println("Must not be a negative.");
}
}
关于java - 错误处理停止程序,但我希望程序继续 Java 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51941156/