簡體   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