When to use an assertion and when to use an exception

前端 未结 11 2078
暖寄归人
暖寄归人 2020-11-27 09:28

Most of the time I will use an exception to check for a condition in my code, I wonder when it is an appropriate time to use an assertion?

For instance,



        
11条回答
  •  时光取名叫无心
    2020-11-27 09:30

    Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen.

    For example, a function might divide by 0, so an exception should be used, but an assertion could be used to check that the harddrive suddenly disappears.

    An assertion would stop the program from running, but an exception would let the program continue running.

    Note that if(group != null) is not an assertion, that is just a conditional.

提交回复
热议问题