【问题标题】:avoid Negative Array Size Exception with try, catch and throw使用 try、catch 和 throw 避免负数组大小异常
【发布时间】:2019-01-23 10:30:54
【问题描述】:

以下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 新手,所以会很感激任何帮助。

谢谢

【问题讨论】:

    标签: arrays try-catch throw


    【解决方案1】:

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

    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());
                  }
              }
           }
        }
    

    输出将是

    【讨论】:

    • 嗨,感谢您的意见。但是,它不允许我运行代码,因为我在第 7 行遇到错误。说“main.this 不能从静态上下文中引用”......我该怎么办?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多