Debug.Assert vs Exception Throwing

前端 未结 8 1404
囚心锁ツ
囚心锁ツ 2020-12-12 10:49

I\'ve read plenty of articles (and a couple of other similar questions that were posted on StackOverflow) about how and when to use assertions, and I understood the

8条回答
  •  渐次进展
    2020-12-12 11:37

    EDIT: In response to the edit/note you made in your post: It sounds like using exceptions are the right thing to use over using assertions for the type of things you are trying to accomplish. I think the mental stumbling block you are hitting is that you are considering exceptions and assertions to fulfill the same purpose, and so you are trying to figure out which one would be 'right' to use. While there may be some overlap in how assertions and exceptions can be used, don't confuse that for them being different solutions to the same problem- they aren't. Assertions and Exceptions each have their own purpose, strengths, and weaknesses.

    I was going to type up an answer in my own words but this does the concept better justice than I would have:

    C# Station: Assertions

    The use of assert statements can be an effective way to catch program logic errors at runtime, and yet they are easily filtered out of production code. Once development is complete, the runtime cost of these redundant tests for coding errors can be eliminated simply by defining the preprocessor symbol NDEBUG [which disables all assertions] during compilation. Be sure, however, to remember that code placed in the assert itself will be omitted in the production version.

    An assertion is best used to test a condition only when all of the following hold:

    * the condition should never be false if the code is correct,
    * the condition is not so trivial so as to obviously be always true, and
    * the condition is in some sense internal to a body of software.
    

    Assertions should almost never be used to detect situations that arise during software's normal operation. For example, usually assertions should not be used to check for errors in a user's input. It may, however, make sense to use assertions to verify that a caller has already checked a user's input.

    Basically, use exceptions for things that need to be caught/dealt with in a production application, use assertions to perform logical checks that will be useful for development but turned off in production.

提交回复
热议问题