【问题标题】:Error handling stops the program, however I want the program to continue with the loop in Java错误处理会停止程序,但是我希望程序继续 Java 中的循环
【发布时间】:2019-01-27 04:45:03
【问题描述】:

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

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

由于数组大小为负数而发生错误,但是我该如何继续完成循环?

【问题讨论】:

  • 将异常放入for-loop

标签: java error-handling


【解决方案1】:

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

好的。然后将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.");
    }
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      只需将 try-catch 块放入循环中即可。这样,如果抛出错误,您可以处理它并继续循环。代码如下:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-16
        • 1970-01-01
        • 1970-01-01
        • 2015-04-17
        • 1970-01-01
        • 2013-10-17
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多