Debug.Assert vs Exception Throwing

前端 未结 8 1398
囚心锁ツ
囚心锁ツ 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:29

    Use assertions for things which ARE possible but should not happen (if it were impossible, why would you put an assertion?).

    Doesn't that sound like a case to use an Exception? Why would you use an assertion instead of an Exception?

    Because there should be code that gets called before your assertion that would stop the assertion's parameter being false.

    Usually there is no code before your Exception that guarantees that it won't be thrown.

    Why is it good that Debug.Assert() is compiled away in prod? If you want to know about it in debug, wouldn't you want to know about it in prod?

    You want it only during development, because once you find Debug.Assert(false) situations, you then write code to guarantee that Debug.Assert(false) doesn't happen again. Once development is done, assuming you've found the Debug.Assert(false) situations and fixed them, the Debug.Assert() can be safely compiled away as they are now redundant.

提交回复
热议问题