Why should I use asserts?

后端 未结 19 1900
遇见更好的自我
遇见更好的自我 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:12

    Assertion should be used when you do something like this

    a = set()
    a.add('hello')
    assert 'hello' in a
    

    or

    a = 1;
    assert a == 1; // if ram corruption happened and flipped the bit, this is the time to assert
    

    As for exceptions, it's something you programmatically deal with:

    while True:
      try:
        data = open('sample.file').read()
        break // successfully read
      except IOError:
        // disk read fail from time to time.. so retry
        pass
    

    Most of the time it's safer to restart your application when assert happens, because you don't want to deal with impossible cases. But when the expected case happens (expected errors (most of the time from black-box clients, network calls, etc..) the exceptions should be used.

提交回复
热议问题