MissioDei
MissioDei

Reputation: 809

Why does this block throw an error?

"Not all code paths return a value"

 public BallData GetBall(String Name)
    { 
        //Check each item in the list for the name.
        foreach (BallData Item in _BallList)
        {
            //If the name matches, return the item to the caller and exit the loop.
            if (Item.Name == Name)
            {
                return Item;
            }
            else
            {
                // Otherwise, throw an exception to indicate that the ball wasn't found.
                throw new KeyNotFoundException("The ball name doesn't exist.");
            }


        }
    }

Upvotes: 0

Views: 82

Answers (3)

Mithrandir
Mithrandir

Reputation: 25357

Change your code to:

 foreach (BallData Item in _BallList)
 {
            //If the name matches, return the item to the caller and exit the loop.
            if (Item.Name == Name)
            {
                return Item;
            }

  }
  throw new KeyNotFoundException("The ball name doesn't exist.");

Upvotes: 5

Didier Ghys
Didier Ghys

Reputation: 30666

If _BallList is empty, you'll never get into the loop and thus the method does not return anything

Upvotes: 3

empi
empi

Reputation: 15881

If _BallList is empty then nothing is returned.

Upvotes: 1

Related Questions