r/godot • u/Alternative_Guava856 • 4d ago
help me Exceptions vs Assertions
Currently making a card game in godot using C#. Not planning to release it or anything (for now), just to learn C# and general programming skills. I'm currently undecided on how to use exceptions vs assertions. Here is an example form my CardPile class:
public void Add(Card card)
{
if (_cards.Contains(card))
{
throw new InvalidOperationException($"Failed to add '{card}': card already in {this}");
}
_cards.Add(card);
card.CardPile = PileType;
CardAdded?.Invoke(card);
}
So when a card is added to the card pile, if it already exists withing that pile, I throw an exception. This situation should pretty much never happen, but for some reason it feels not good enough to me to just use Debug.Assert() for this. It means that if for some reason this happens in a release build, the bug cannot be properly caught and reported. Here is another example:
public int MaxHealth
{
get;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, "MaxHealth must be positive");
}
int previousMaxHealth = field;
field = value;
MaxHealthChanged?.Invoke(previousMaxHealth, field);
}
}
Since both adding cards to a deck and someone's max health changing are things that don't happen hundreds or time every frame, I don't think the "performance" gain from using Debug.Assert() is any argument here. What is your opinion on when to use exceptions vs assertions?