Search code examples
arraystry-catchthrow

avoid Negative Array Size Exception with try, catch and throw


The following Java code:

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

The first two instances of SomeClass, which have size 5 and 3, will be created without a problem. However, when the constructor SomeClass is called with an argument of -2, a run time error is generated: NegativeArraySizeException.

how can i modify the above code so that it behaves more robustly by using try, catch and throw. The main method should catch this exception and print a warning message then continue execution of the loop.

im a java newbie so would appreciate any help.

thanks


Solution

  • make the class constructor throw the error and catch it in the main class , like this :

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

    the output would be

    like this.