Java自定义InvalidInputException异常失效问题求助
问题:自定义异常无论输入正确与否都会抛出
我自定义的InvalidInputException异常无法正常工作。我以productName字符串为参数创建Product对象并存入productAvailable列表,让用户输入要更新的产品名称后调用searchProduct方法查找。该方法用迭代器查找对应名称的产品,预期未找到时抛出异常,通过布尔值判断产品是否存在,但现在不管输入正确与否都会抛出异常——比如输入已存入列表的正确名称"Apple"时,也会触发异常捕获。我希望只有输入错误时才抛出异常,求解决办法。
相关代码
1. searchProduct方法
public static void searchProduct(String name) throws InvalidInputException{ Iterator<Product> itr = productAvailable.iterator(); boolean productIsNotThere = true; while (itr.hasNext()) { if (itr.next().getProductName().equals(name)) { productIsNotThere = false; } } if(productIsNotThere) { throw new InvalidInputException("The product you are looking for is no longer in stock or this is not the right product name"); } } //if the product is there it should send a message, if not throw an exception with a message)
2. 产品初始化代码
Product apple = new Product("111111", "Apple", 1, 100); //构造方法:Product(productID, ProductName, price, quantity) Collections.addAll(Inventory_Management.getProductAvailable(), apple, kiwi, banana);
3. 调用代码
System.out.println("Give me the product name of the product you want to update"); String name = "Apple"; try { Inventory_Management.searchProduct(name); } catch(InvalidInputException e) { e.printStackTrace(); }
解决方案
核心问题分析
你的代码存在两个关键问题:
- 列表引用不匹配:
getProductAvailable()可能返回的是新列表而非searchProduct方法使用的静态productAvailable列表,导致添加的产品根本没进入目标遍历列表。 - 遍历逻辑冗余:找到匹配产品后未终止循环,虽然不会改变
productIsNotThere的值,但会做无意义遍历,且后续代码变更可能引入未知问题。
修复步骤
- 修正遍历逻辑,找到匹配后立即终止循环
修改searchProduct方法,找到目标产品后跳出循环,避免不必要的遍历:
public static void searchProduct(String name) throws InvalidInputException{ Iterator<Product> itr = productAvailable.iterator(); boolean productIsNotThere = true; while (itr.hasNext()) { Product currentProduct = itr.next(); if (currentProduct.getProductName().equals(name)) { productIsNotThere = false; break; // 找到匹配项后立即终止循环 } } if(productIsNotThere) { throw new InvalidInputException("你查找的产品已缺货或产品名称错误"); } }
- 确认列表引用一致性
检查getProductAvailable()方法的实现,确保它直接返回静态productAvailable列表的引用,而非新创建的列表:
// 正确实现示例 public static List<Product> getProductAvailable() { return productAvailable; // 返回原列表引用,而非new ArrayList<>(productAvailable) }
如果返回的是新列表,你通过Collections.addAll添加的产品不会进入searchProduct遍历的productAvailable列表,导致永远找不到产品抛出异常。
- 可选:支持大小写不敏感匹配
如果需要忽略产品名称的大小写(比如输入"apple"也能匹配"Apple"),可以将equals(name)替换为equalsIgnoreCase(name):
if (currentProduct.getProductName().equalsIgnoreCase(name)) { // ... }
内容的提问来源于stack exchange,提问作者Kenny
相关产品推荐
相关产品推荐

