When to use an assertion and when to use an exception

前端 未结 11 2086
暖寄归人
暖寄归人 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:41

    Testing for null will only catch nulls causing problems, whereas a try/catch as you have it will catch any error.

    Broadly, try/catch is safer, but slightly slower, and you have to be careful that you catch all the kinds of error that may occur. So I would say use try/catch - one day the getGroup code may change, and you just might need that bigger net.

提交回复
热议问题