Search code examples
javaarraysindexoutofboundsexception

Is there a way to replace an ArrayIndexOutOfBoundsException causing value to some default value?


I'm trying to replace the ArrayIndexOutOfBounds-causing value to 0.

The output that I'm hoping to get is:

0
10
20
30
40
0
0
0
0
0

Is there a way to achieve this?

Please note that I do not want this for the purpose of printing (which I could do by doing a System.out.println("0") in the catch block.

public class test {
  int[] array;

  @Test
  public void test() {
    array = new int[5];
    for (int i = 0; i < 5; i++) {
      array[i] = i;
    }

    for(int i = 0; i < 10; i++) {
      try {
        System.out.println(array[i] * 10);
      }
      catch(ArrayIndexOutOfBoundsException e) {
        //code to replace array[i] that caused the exception to 0
      }
    }
  }
}


Solution

  • Exceptions like ArrayIndexOutOfBounds generally mean there is a mistake in your code; you should treat them as cases where you need to "ask permission" first by checking the index before you access the array, rather than "seek forgiveness" by catching the exception.

    Object-oriented programming is all about encapsulation of the behaviour you want. An array doesn't behave this way, so you can't use an array directly for this purpose. However, if you want something which does behave this way (i.e. it returns a default value when you access a non-existent index) then invent your own type of thing which does that. For example:

    public class DefaultArray {
        private final int defaultValue;
        private final int[] array;
    
        public DefaultArray(int length, int defaultValue) {
            this.array = new int[length];
            this.defaultValue = defaultValue;
        }
    
        public int get(int i) {
            // ask permission!
            if(i >= 0 && i < array.length) {
                return array[i];
            } else {
                return defaultValue;
            }
        }
        public void set(int i, int value) {
            array[i] = value;
        }
        public int length() {
            return array.length;
        }
    }
    

    Usage:

    DefaultArray arr = new DefaultArray(5, 0);
    for(int i = 0; i < 5; i++) {
        arr.set(i, i);
    }
    for(int i = 0; i < 10; i++) {
        System.out.println(arr.get(i) * 10);
    }
    

    Output:

    0
    10
    20
    30
    40
    0
    0
    0
    0
    0