Throw helpers with a "reason (string)" overload? #121375
-
|
code:
we can't replace it with would be nice if we could give reasons to the exception throw helpers. Or is there a reason this is not added? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
It is not a good choice to use the throw helper in such case. The exception |
Beta Was this translation helpful? Give feedback.
-
|
Also, you would open the door to unwanted string allocations. E.g.: // Always creates a string to be GC'ed
ArgumentOutOfRangeException.ThrowIfGreaterThan(
depth,
0,
nameof(depth),
$"Comment tag is not closed (depth = {depth})" // :-(
);I just fixed such a performance bug in our codebase. |
Beta Was this translation helpful? Give feedback.
It is not a good choice to use the throw helper in such case. The exception
ArgumentOutOfRangeExceptionis for argument, which means the reason should be an input argument of a method is in correct. In this case, the called method and argument name is almost the whole reason.It should not be used for representing bad state after doing complex logic. A different exception type like
ParseExceptionshould be used instead.