Try/catch vs. If best practices

In this lecture, a try/catch is executed because we know that we’ll be referencing a dictionary item that might not exist.

It’s also possible to check if the object exists with a statement like this one:

if (grid.ContainsKey(explorationCoordinates))

This would check safety before executing and simply not complete if the position does not exist. However, if there are other reasons why the dictionary positions might not be accessible, we’ll get an error that isn’t “caught”.

I’ve used basic checks like the if command above forever, but it doesn’t feel quite as safe. Does anyone have a feeling on the best way to handle these situations?

1 Like

This would be the best approach, if you need the Value of the Key you are searching:

if(grid.TryGetValue(explorationCoordinats, out Waypoint foundWaypoint)))
{
    foundWaypoint.SetTopColor(Color.black);
}
else
{
    Debug.Log("No Waypoint found with given coordinates");
}

With your approach, you search the dictionary if the Key exists, and then you still need to get the value out of the dictionary, so you search it 2 times.

TryGetValue itself searches also 2 Times, but it does it for you, so your code is more readable

Your Approach:

if (grid.ContainsKey(explorationCoordinates))
{
   grid[explorationCoordinates].SetTopColor(Color.Black);
}
else
{
    Debug.Log("No Waypoint found with given coordinates");
}

As you can see, you also don’t have the Waypoint extracted, and can not work with it, Calling other methods etc…

With TryGetValue, you can work with the Waypoint and call other methods

Privacy & Terms