错误处理会停止程序,但是我希望程序继续在 Java 中循环

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


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

        }

    }

}

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


catspeake
浏览 163回答 3
3回答

慕哥6287543

但是我希望让它完成循环而不是在错误被捕获时停止。好的。然后将try和移动catch 到循环中。for (int i = 0; i < 6; i++) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; testInst = new myClass(sizes[i]);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("New example size " + testInst.size);&nbsp; &nbsp; } catch (NegativeArraySizeException e) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Must not be a negative.");&nbsp; &nbsp; }}

繁花如伊

首先指定程序中的位置可以抛出异常。其次指定如何处理异常,例如指定您要抛出该异常还是只写日志并继续执行。第三,您指定何时处理异常。在您的代码中,try-catch 可以在构造函数中,也可以在循环和下面的代码中,以达到您的目标。testInst = new myClass(sizes[i]);

慕仙森

只需将 try-catch 块放入循环中即可。这样,如果抛出错误,您可以处理它并继续循环。这是代码:&nbsp; &nbsp; public class myClass {&nbsp; &nbsp; int[] table;&nbsp; &nbsp; int size;&nbsp; &nbsp; public myClass(int size) {&nbsp; &nbsp; &nbsp; &nbsp; this.size = size;&nbsp; &nbsp; &nbsp; &nbsp; table = new int[size];&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; int[] sizes = {5, 3, -2, 2, 6, -4};&nbsp; &nbsp; &nbsp; &nbsp; myClass testInst;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 6; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; testInst = new myClass(sizes[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("New example size " + testInst.size);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch(NegativeArraySizeException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Must not be a negative.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java