When to use an assertion and when to use an exception

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

    Well, back at Microsoft, the recommendation was to throw Exceptions in all APIs you make available publicly and use Asserts in all sorts of assumptions you make about code that's internal. It's a bit of a loose definition but I guess it's up to each developer to draw the line.

    Regarding the use of Exceptions, as the name says, their usage should be exceptional so for the code you present above, the getGroup call should return null if no service exists. Exception should only occur if a network link goes down or something like that.

    I guess the conclusion is that it's a bit left down to the development team for each application to define the boundaries of assert vs exceptions.

提交回复
热议问题