1

I have this method that returns a Recipe object if found by name in my Menu array. If it doesnt find it, it throws a custom RecipeNotFoundException and just says it isnt found...

public static Recipe getRecipe(String recipeName){

    try{

        for(int j = 0 ; j < Menu.length ; j++){

            if(Menu[j].getName().equals(recipeName)){

                return (Recipe)Menu[j];

            }

            else{

                throw new RecipeNotFoundException();

            }
        }

}catch(RecipeNotFoundException e){

    System.out.println("Recipe Not Found!");

}   

    return null;

}

Under its current condition it only checks the first Menu spot, how do I make it check all of them before throwing the exception!? I've tried inverting and floping but it just leads to NullPointerExceptions and checking the whole thing without being able to do the throwing. Any one got some guidance? Thanks in advance!

Sherifftwinkie
  • 391
  • 1
  • 13
  • 21

1 Answers1

3

Throw your exception after the whole loop is complete:

for (int j = 0; j < Menu.length; j++) {
    if (Menu[j].getName().equals(recipeName)) {
        return (Recipe) Menu[j];
    }
}
throw new RecipeNotFoundException();

If it find a recipe, it will return before it reaches the line to throw the exception.

Of course, throwing an exception here is a little pointless. If you aren't doing anything else, you could just add your error handling code after the loop instead of throwing your exception, since it's just caught within the same method, anyway. You usually throw exceptions when you want the error to be handled by the method's caller, not the method itself.

Alexis King
  • 43,109
  • 15
  • 131
  • 205