为什么我创建的异常在Java中不起作用?

问题描述 投票:0回答:1

我创建了一个不起作用的异常:这里我创建了一个产品对象,并以 ProductName 字符串变量作为参数。我将产品放入名为productAvailable 的列表中。我询问用户他们想要更新哪个产品,并告诉他们写下产品的名称。然后,我使用方法(searchProduct)来搜索是否存在该名称的产品。该程序使用迭代器来搜索是否存在具有productName 的产品,如果没有则应该抛出异常。布尔值用于查明产品是否存在。但它始终有效。 即使我写了正确的输入,它也会抛出一个被捕获的异常。这里的“Apple”应该等于列表中的产品名称,并且不会引发异常。我不明白为什么这样做。请帮忙。预先感谢。

我希望异常仅在我输入错误时才起作用。

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)
        Product apple = new Product("111111", "Apple", 1, 100); 
        //contructor : Product( productID, ProductName, price, quantity)

        Collections.addAll(Inventory_Management.getProductAvailable(), apple, kiwi, banana);
 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();
                }```
java exception user-input
1个回答
0
投票

我看到的代码看起来没问题。呼唤

            throw new InvalidInputException("...");

肯定会引发异常,因此一定不能调用该代码。 一个简单的测试是将 if 语句逻辑更改为:

        if(productIsNotThere || true) {
            throw new InvalidInputException("The product you are looking for is no longer in stock or this is not the right product name");
        }

我的猜测是逻辑中的其他内容不正确

productIsNotThere == false

© www.soinside.com 2019 - 2024. All rights reserved.