java - 错误处理停止程序,但我希望程序继续 Java 中的循环

标签 java error-handling

我有一个程序可以运行并捕获错误,但是我希望它完成循环并且在捕获错误时不会停止。

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.");
        }
    }
}

错误发生在数组大小为负数时,但我该如何继续完成循环?

最佳答案

但是我希望让它完成循环并且在捕获到错误时不停止。

好的。然后将 trycatch 移到循环中。

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/

相关文章:

PHP 关闭错误 - 仅在一个文件中

java - android ViewFlipper - 具有异步图像加载的图像幻灯片

更改操作系统时间时 sleep() 中的 Java 错误 : any workaround?

javascript - 如何在 MERN 堆栈中向用户显示错误

java - Java Web 服务返回错误

linux - 如何安装 Proc::Daemon 模块

amazon-web-services - AWS Step Functions 未捕获 States.Runtime 错误

java.util.ConcurrentModificationException - ArrayList

java - 如果我将结果集传递给表模型,如何在 MyTableModel 中使用 setValueAt()

java - Optional.ofNullable() 中的空指针异常