没有抛出我的自定义异常,而是抛出了 ArrayOutOfBoundsException(JunitTest 错误)

My Custom Exception is not thrown, instead the ArrayOutOfBoundsException Is thrown (JunitTest Error)

我的自定义异常有问题,我想在输入的 row/col 不存在于我的 shelf[][] 中时抛出自定义异常,这只是一种工作方式。当我编译我的 main(错误消息被打印)时,自定义异常确实被抛出 - 即使我的代码中的抛出部分显然从未达到(https://i.stack.imgur.com/1OY52.png) - 但它也会抛出 ArrayIndexOutOfBoundsException。因此,当我 Junit 测试我的抛出 InvalidRow/ColumnException 方法时,它失败了,因为它抛出了 ArrayOutOfBoundsException。 我该如何解决这个问题,这样我的 Junit 测试 assertThrows(InvalidRowException.class,() -> shelf.addItem(3, 0, bottle)); 就不会捕获 ArrayIndexOutOfBoundsException,而只会捕获我的 InvalidRowException?

这是我的例外 Class:

public class InvalidRowException extends ArrayIndexOutOfBoundsException {

public InvalidRowException(int wrongRow){
    super("passed Row " + wrongRow + " doesnt excist.");
}

}

这是我的方法

public void addItem(int row, int coll, Product product) throws InvalidRowException, InvalidColumnException {
    if (row < 0 | row > shelf.length)
        throw new InvalidRowException(row);
    if (coll < 0 | coll > shelf[1].length)
        throw new InvalidColumnException(coll);
    try {

        if (!(product instanceof Placeable)) {
            throw new ProductNotPlaceableException(product);
        } else if (shelf[row][coll] != null) {
            System.out.println("Replacing product with serial " + shelf[row][coll].getSerialNumber()
                    + " by product with serial " + product.getSerialNumber());
            shelf[row][coll] = product;
        } else {
            shelf[row][coll] = product;
        }

    } catch (ProductNotPlaceableException e) {
        System.out.println(e.getMessage());
    }
}

您抛出异常 行 > shelf.length

您应该检查行 > shelf.length -1,因为数组是基于 0 的

与 coll 类似,正确的检查是 coll> shelf[row].length-1