简体   繁体   English

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

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

I have an extremely basic function which searches through an ArrayList of CustomerAccount , and returns the accounts matching the regNum argument is passed to it. 我有一个非常基本的功能,它通过CustomerAccount的ArrayList搜索,并返回与regNum参数匹配的帐户。 However, as soon as the CustomerAccountNotFoundException is thrown, my for loop breaks. 但是,一旦引发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've tested this by printing the value of i after an Exception, which keeps being reset to 0. How can I continue the loop after the Exception is thrown? 我已经通过在异常之后打印i的值进行了测试,该值一直被重置为0。抛出异常后,如何继续循环? I want it thrown each time the account doesn't match, and the account returned when it does. 我希望每次帐户不匹配时都将其抛出,当帐户匹配时将其返回。 I've also tried continue; 我也尝试过continue; which doesn't work. 这不起作用。

Based on your described logic, you should only throw the exception after the loop is done (if no match was found): 根据您描述的逻辑,只应在循环完成后抛出异常(如果未找到匹配项):

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();
}

You can't throw multiple exceptions from a method after invoking it once. 调用一次后,您不能从一个方法引发多个异常。

Once an exception is thrown you exit the scope so cannot then throw another. 引发异常后,您将退出范围,因此无法再引发另一个异常。

What you can do in your particular case is throw the exception if customer is null at the end of your loop. 如果客户在循环结束时为null,则在特定情况下可以执行的操作将引发异常。

Remove the CustomerNotFoundException from throws class.Catch the exception in the else block only as it seems to be of no use and put continue after the catch of exception. 从throws类中删除CustomerNotFoundException,仅在else块中捕获该异常没有用,并在捕获异常后继续继续,否则将其捕获在else块中。 Not clear the use of throwing the exception as you still want to continue through the loop. 由于您仍想继续执行循环,因此不清楚使用引发异常的方法。 Throwing the exception in your code would return to the parent method. 在代码中引发异常将返回父方法。

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

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