如何在不中断 for 循环的情况下抛出异常?

How do you throw an Exception without breaking a for loop?

我有一个非常基本的功能,它搜索 CustomerAccount 的 ArrayList,并且 returns 匹配 regNum 参数的帐户被传递给它。但是,一旦抛出 CustomerAccountNotFoundException,我的 for 循环就会中断。

public CustomerAccount findCustomer(String regNum) throws CustomerNotFoundException
{
    CustomerAccount customer = null;
    for (int i=0; i < accounts.size(); i++)
    {
        if(regNum.equals(accounts.get(i).getCustomerVehicle().getRegistration()))
        {
            customer = accounts.get(i);
        }
        else
        {
            throw new CustomerNotFoundException();
        }
    }
    return customer;
}

我已经通过在异常后打印 i 的值来测试它,该值一直重置为 0。抛出异常后如何继续循环?我希望每次帐户不匹配时抛出它,并在匹配时返回帐户。我也试过 continue; 没用。

根据您描述的逻辑,您应该只在循环完成后抛出异常(如果未找到匹配项):

public CustomerAccount findCustomer(String regNum) throws CustomerNotFoundException
{
    for (int i=0; i < accounts.size(); i++)
    {
        if(regNum.equals(accounts.get(i).getCustomerVehicle().getRegistration()))
        {
            return accounts.get(i);
        }
    }
    throw new CustomerNotFoundException();
}

一个方法调用一次后不能抛出多个异常。

一旦抛出异常,您就会退出范围,因此无法再抛出另一个异常。

在您的特定情况下,您可以做的是在循环结束时如果 customer 为 null 则抛出异常。

从抛出 CustomerNotFoundException 中删除 class.Catch else 块中的异常,因为它似乎没有用,并在捕获异常后继续。 不清楚抛出异常的用途,因为您仍想继续循环。 在您的代码中抛出异常会 return 到父方法。