Closed Bilge closed 6 years ago
Exceptions are for exceptional behavior, not for normal control flow. If you handle these cases differently, it means that they're not exceptions, but regular cases. Consider using singleOrDefault
(it returns the only element of a sequence, or a default value if the sequence contains no elements) or some combination of first
, firstOrDefault
, count
etc., depending on what cases your code handles.
Exceptions are very expensive and handling them requires complex syntax. Don't use them for control flow.
That's a good point, and I probably do want singleOrDefault()
here. However, this does not invalidate the point that distinct exception types should be thrown instead of shared between different cases.
single()
currently throwsUnexpectedValueException
for two distinct cases:It is still possible to distinguish these exception cases by exception message, but it is preferable to catch different types rather than inspect the message because messages are subject to change and type comparison is faster, more succinct to write and clearer.