首页 > 解决方案 > 使用 try、catch 和 throw 避免负数组大小异常

问题描述

以下 Java 代码:

   public class SomeClass {
   int[] table;
   int size;

   public SomeClass(int size) {
      this.size = size;
      table = new int[size];
   }

   public static void main(String[] args) {
      int[] sizes = {5, 3, -2, 2, 6, -4};
      SomeClass testInst;
      for (int i = 0; i < 6; i++) {
         testInst = new SomeClass(sizes[i]);
         System.out.println("New example size " + testInst.size);
      }
   }
}

SomeClass 的前两个实例的大小为 5 和 3,将毫无问题地创建。但是,当使用参数 -2 调用构造函数 SomeClass 时,会生成运行时错误:NegativeArraySizeException。

如何修改上述代码,使其通过使用 try、catch 和 throw 表现得更加稳健。main 方法应捕获此异常并打印警告消息,然后继续执行循环。

我是一个java新手,所以会很感激任何帮助。

谢谢

标签: arraystry-catchthrow

解决方案


使类构造函数抛出错误并在主类中捕获它,如下所示:

public class SomeClass {

int[] table;
int size;

   public SomeClass(int size) throws NegativeArraySizeException{
          this.size = size;
          table = new int[size];
       }


   public static void main(String[] args) {
          int[] sizes = {5, 3, -2, 2, 6, -4};
          SomeClass testInst;
          for (int i = 0; i < 6; i++) {
              try {
                  testInst = new SomeClass(sizes[i]);
                   System.out.println("New example size " + testInst.size);
              } 
              catch (NegativeArraySizeException err) {
                  System.out.println(err.toString());
              }
          }
       }
    }

输出将是

像这样。


推荐阅读