1

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. However, as soon as the CustomerAccountNotFoundException is thrown, my for loop breaks.

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 want it thrown each time the account doesn't match, and the account returned when it does. I've also tried continue; which doesn't work.

eddiewastaken
  • 822
  • 8
  • 23
  • Related: [Fetch first element which matches criteria](https://stackoverflow.com/questions/22940416/fetch-first-element-which-matches-criteria) – Bernhard Barker Apr 25 '18 at 11:11
  • "How do you throw an Exception without breaking a for loop?" -> you can't. But you can redesign your code to match more the logic you want. See [Eran Answer](https://stackoverflow.com/a/50020339/5914654) – vincrichaud Apr 25 '18 at 11:22

3 Answers3

4

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();
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

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.

Sam
  • 670
  • 1
  • 6
  • 20
0

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. 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.

Piyush Upadhyay
  • 427
  • 4
  • 12