繁体   English   中英

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

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

我有一个非常基本的功能,它通过CustomerAccount的ArrayList搜索,并返回与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();
}

调用一次后,您不能从一个方法引发多个异常。

引发异常后,您将退出范围,因此无法再引发另一个异常。

如果客户在循环结束时为null,则在特定情况下可以执行的操作将引发异常。

从throws类中删除CustomerNotFoundException,仅在else块中捕获该异常没有用,并在捕获异常后继续继续,否则将其捕获在else块中。 由于您仍想继续执行循环,因此不清楚使用引发异常的方法。 在代码中引发异常将返回父方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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