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

后端 未结 7 745
误落风尘
误落风尘 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 17:06

    Short answer:
    Neither

    Longer answer:
    using Argument*Exception (except in a library that is a product on its on, such as component library) is a smell. Exceptions are to handle exceptional situation, not bugs, and not user's (i.e. API consumer) shortfalls.

    Longest answer:
    Throwing exceptions for invalid arguments is rude, unless you write a library.
    I prefer using assertions, for two (or more) reasons:

    • Assertions don't need to be tested, while throw assertions do, and test against ArgumentNullException looks ridiculous (try it).
    • Assertions better communicate the intended use of the unit, and is closer to being executable documentation than a class behavior specification.
    • You can change behavior of assertion violation. For example in debug compilation a message box is fine, so that your QA will hit you with it right away (you also get your IDE breaking on the line where it happens), while in unit test you can indicate assertion failure as a test failure.

    Here is what handling of null exception looks like (being sarcastic, obviously):

    try {
        library.Method(null);
    }
    catch (ArgumentNullException e) {
        // retry with real argument this time
        library.Method(realArgument);
    }
    

    Exceptions shall be used when situation is expected but exceptional (things happen that are outside of consumer's control, such as IO failure). Argument*Exception is an indication of a bug and shall be (my opinion) handled with tests and assisted with Debug.Assert

    BTW: In this particular case, you could have used Month type, instead of int. C# falls short when it comes to type safety (Aspect# rulez!) but sometimes you can prevent (or catch at compile time) those bugs all together.

    And yes, MicroSoft is wrong about that.

提交回复
热议问题