Debug.Assert vs Exceptions

前端 未结 8 1152
面向向阳花
面向向阳花 2020-12-13 21:03

Surprisingly I was only able to find one previous question on SO about this subject, and I\'d just like to get the community \"Vote of Confidence\" (or not!) on my approach.

8条回答
  •  感动是毒
    2020-12-13 21:46

    My use of asserts follows ideas from design by contract. Basically, you assert that incoming parameters, globals variables and other state information is valid as you enter your function, and assert the return values and state is also valid as you leave. If you get a failed assert at the start, it is a bug in the calling code, if you get it at the end, the bug is in this code. These are pre-conditions and post conditions.

    An assert in your switch statement is only really useful if you have checked your pre-conditions on entry. If you arrive at an unacceptable state in the middle of your function in this scenario, it is a failing in your function or a called function. Personally, I would stick with an assert here as it is not an exception. As you imply, exceptions relate to resources, not bugs. You can however create a custom assertion handler that exists in the release build and throws an exception on failure, to give your program an opportunity to return to a stable state.

提交回复
热议问题