简体   繁体   中英

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

i have a Problem with my Custom Exception, i want to throw a Custom Exception when the entered row/col does not excist in my shelf[][] which only kind of works. The custom exception does get thrown when i compile my main (error message is printed)- even though the throw part in my Code is apparently never reached ( https://i.stack.imgur.com/1OY52.png ) - but it also throws the ArrayIndexOutOfBoundsException. So when i Junit test my method for throwing InvalidRow/ColumnException it fails because it throws the ArrayOutOfBoundsException. How do i solve this problem so my Junit test assertThrows(InvalidRowException.class,() -> shelf.addItem(3, 0, bottle)); doesnt catch the ArrayIndexOutOfBoundsException but instead only my InvalidRowException?

This is my Exception Class:

public class InvalidRowException extends ArrayIndexOutOfBoundsException {

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

}

This is my Method

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

You throw exception for row > shelf.length

You should check for row > shelf.length -1 as arrays are 0 based

Similarly for coll the correct check is coll> shelf[row].length-1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM