[英]My Custom Exception is not thrown, instead the ArrayOutOfBoundsException Is thrown (JunitTest Error)
我的自定義異常有問題,當輸入的行/列在我的架子[][] 中不存在時,我想拋出一個自定義異常,這只是一種工作。 當我編譯我的 main (打印錯誤消息)時,確實會引發自定義異常 - 即使我的代碼中的 throw 部分顯然從未達到( 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());
}
}
您為 row >shelf.length 拋出異常
您應該檢查 row >shelf.length -1 因為 arrays 基於 0
同樣對於 coll 正確的檢查是 coll>shelf[row].length-1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.