Java 如何在不中断for循环的情况下抛出异常?
我有一个非常基本的函数,它搜索Java 如何在不中断for循环的情况下抛出异常?,java,for-loop,exception,exception-handling,Java,For Loop,Exception,Exception Handling,我有一个非常基本的函数,它搜索CustomerAccount的数组列表,并返回与传递给它的regNum参数匹配的帐户。但是,一旦抛出CustomerAccountNotFoundException,我的for循环就会中断 public CustomerAccount findCustomer(String regNum) throws CustomerNotFoundException { CustomerAccount customer = null; for (int i=0
CustomerAccount
的数组列表,并返回与传递给它的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;
}
public CustomerAccount findCustomer(字符串regNum)引发CustomerNotFoundException
{
CustomerAccount客户=null;
对于(int i=0;i
我通过在异常后打印
I
的值来测试这一点,异常一直被重置为0。抛出异常后,如何继续循环?我希望每次帐户不匹配时都抛出它,当帐户匹配时返回。我还尝试了继续代码>无效。根据您描述的逻辑,您应该仅在循环完成后抛出异常(如果未找到匹配项):
public CustomerAccount findCustomer(字符串regNum)引发CustomerNotFoundException
{
对于(int i=0;i
在调用一次方法后,不能从该方法引发多个异常
一旦抛出异常,您将退出该范围,因此无法再抛出另一个异常
在特定情况下,如果循环结束时customer为null,则可以抛出异常。从throws类中删除CustomerNotFoundException。仅在else块中捕获异常,因为它似乎没有用处,并在捕获异常后继续。
不清楚抛出异常的用法,因为您仍然希望继续循环。
在代码中抛出异常将返回父方法。相关:“如何在不中断for循环的情况下抛出异常?”->您不能。但是你可以重新设计你的代码来匹配你想要的逻辑。看见
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();
}