What exceptions should be thrown for invalid or unexpected parameters in .NET?

后端 未结 7 760
误落风尘
误落风尘 2020-12-22 16:43

What types of exceptions should be thrown for invalid or unexpected parameters in .NET? When would I choose one instead of another?

Follow-up:

Which excep

7条回答
  •  我在风中等你
    2020-12-22 16:58

    Depending on the actual value and what exception fits best:

    • ArgumentException (something is wrong with the value)

    • ArgumentNullException (the argument is null while this is not allowed)

    • ArgumentOutOfRangeException (the argument has a value outside of the valid range)

    If this is not precise enough, just derive your own exception class from ArgumentException.

    Yoooder's answer enlightened me. An input is invalid if it is not valid at any time, while an input is unexpected if it is not valid for the current state of the system. So in the later case an InvalidOperationException is a reasonable choice.

提交回复
热议问题