I have a method where I need to return a specific object if found, otherwise throw an exception. So I wrote the following:
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}else{
throw new CustomerNotFoundException();
}
}
}
But it requires me to add a return statement at the bottom of the method. Is there a way to ignore this?
customersis empty? And do you really want to throw an exception if the very first customer is not the one you want? (That's what your current code would do... you'll never go into a second iteration of the loop.)customerscollection is empty. In that case, neither thereturnnor thethroware executed. You should implement it the wayTheLostMindsuggested below.