Search code examples
javaexceptionspace-efficiency

How to combine exceptions to get rid of repeat code?


How can I minimize the repeated exception throwing code in the code:

public R get(int index) throws IndexException {
  if (!((0 <= index) && (index < this.info.length))) {
    throw new IndexException();
  }
  return this.info[index];
}

public void set(int index, R r) throws IndexException {
  if (!((0 <= index) && (index < this.info.length))) {
    throw new IndexException();
  }
  this.info[index] = r;
}

Solution

  • Create a method that will throw an exception:

    private void checkBounds(int index) throws IndexException {
      if (index < 0 || index >= info.length) {
         throw new IndexException();
      }
    }
    

    You can then call it:

    public R get(int index) throws IndexException {
      checkBounds(index);
      return this.info[index];
    }
    
    public void set(int index, R r) throws IndexException {
      checkBounds(index);
      this.info[index] = r;
    }