When to use assertion over exceptions in domain classes

前端 未结 3 2050
灰色年华
灰色年华 2021-01-06 14:37

Are there any situations when you would use assertion instead of exceptions-handling inside domain classes...

3条回答
  •  旧巷少年郎
    2021-01-06 15:44

    An assertion reflects a state that should not ever occur and was not expected, where the application cannot continue executing for one reason or another, whereas an exception indicates a state that is not considered "normal", but that was not unexpected, and from which it might be possible to recover.

    As an example, if I allocate space on the heap, and this allocation fails, then I can't continue working, so I assert that the address returned is valid; where it is invalid, the assertion fails, and the program fails with it.

    On the other hand, if I open a file for reading, and it doesn't exist, then it might be possible to recover from the situation, in which case an exception is thrown (and caught, and handled as far as possible).

    In general, assertions are most useful during the debugging phase, whereas exceptions are considered part of regular program flow and error handling. The general consensus is that assertions should be disabled in production code (to shield users from apparent crashes), whereas I have read a school of thought that argues this is counter-productive, and that the user should see the assertion failure, so that they can properly report the problem.

    Personally, I sometimes combine the two techniques; usually, if I'm catching an exception that I do not believe could be thrown. Taking the example above, if I check the file's existence before attempting to open it, then I do not expect an exception to be thrown, and if one is, then I tend to deal with this by raising an assertion in the relevant catch block. I find this a particularly useful technique in Java, where such exceptions are fully checked.

提交回复
热议问题