Why should I use asserts?

后端 未结 19 2034
遇见更好的自我
遇见更好的自我 2020-12-12 13:47

I never got the idea of asserts -- why should you ever use them?

I mean, let\'s say I were a formula driver and all the asserts were things like security belt, helm

19条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 14:18

    Andrew Koenig used to have a good philosophical discussion over the usage of exceptions and assertions in shipping code. In the end, you're guarding against doing wild things when the program is in an irreparably broken state.

    I believe, therefore, that when a program discovers something that is irrefutably wrong with its internal state, it is better off terminating at once, rather than giving its caller the opportunity to pretend that nothing is wrong.

    If you like, I think that exceptions should be reserved for situations in which it is possible to do something sensible after catching the exception. When you discover a condition that you thought was impossible, it's hard to say much about what might happen afterward.

提交回复
热议问题