Reputation: 1069
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?
Upvotes: 0
Views: 81
Reputation: 1721
If the customer could not be found in the loop, it should throw exception out of the loop. Also you should use ".equals" instead of "==", because "givenID" is an object.
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException {
for (CustomerDetails nextCustomer : customers) {
if (givenID.equals(nextCustomer.getCustomerID())){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
}
Upvotes: 0
Reputation: 339
You can just add a return;
at the end of your method. It won't be accessible so it won't cause issues.
You could also use a try catch around your loop. Here is a handy tutorial for that if you wish to follow this route. http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html
Upvotes: 0
Reputation: 395
An exception should be thrown if an unexpected behavior occurs. A failed search is not an exception, but a rarely common cause.
For the reason of good design, you should not throw the exception. Instead you can expand your calling method to test the result for null-iness or similiar.
Upvotes: 0
Reputation: 69495
You can return the object if it is found. If it will be not found it throw an exception at end of the loop:
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID.equals(nextCustomer.getCustomerID())){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
}
Note. you compare strings
with ==
. Here you have to usethe equals
method!
Upvotes: 1
Reputation: 36304
Change your code to :
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
}
Upvotes: 3
Reputation: 62874
It asks you to provide a valid outcome from the method for the case when the loop is not executed (i.e. customers
is empty). You have to do this:
for (CustomerDetails nextCustomer : customers){
if (givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
because otherwise you would throw the exception after the first element that doesn't meet the condition provided in the if
.
Upvotes: 6