Exception handling when calling the super class constructor and methods

Viewed 448

For example, I have a parent class that is constructed as:

public class ArrayIndexedList<T> implements IndexedList<T> {

  private final T[] data;

  public ArrayIndexedList(int size, T defaultValue) throws LengthException {
    if (size <= 0) {
      throw new LengthException();
    }
    if (defaultValue == null) {
      return;
    }
    for (int i = 0; i < size; i++) {
      data[i] = defaultValue;
    }
  }

}

And I have a subclass that extends this class constructed as following:

public class MeasuredIndexedList<T> extends ArrayIndexedList<T> {

  private int accessCount;
  private int mutationCount;

  public MeasuredIndexedList(int size, T defaultValue) {
    super(size, defaultValue); //how to take the exception thrown by this line? 
    accessCount = 0;
    mutationCount = 0;
  }

}

What is the most appropriate way that I can handle the exception form calling the super constructor while not changing the declaration of the subclass constructor?

1 Answers

You can't. At least not if it's a checked exception. (Any exception that is a subclass of Exception, but not RuntimeException) Then you're only option is to pass the exception upwards using throws Exception.

If it's an unchecked exception (Any exception that is a subclass of RuntimeException) you won't have to do anything.

A good example is the ArrayList with it's ArrayList(int capacity) constructor. It will throw an IllegalArgumentException if capacity is smaller than 0. This is a unchecked exception so it's up to the caller whether he wants to catch it or not.

Related