“Ask forgiveness not permission” - explain

前端 未结 8 1593
长情又很酷
长情又很酷 2020-11-22 02:02

I\'m not asking for personal \"religious\" opinions about this philosophy, rather something a bit more technical.

I understand this phrase is one of several litmus t

相关标签:
8条回答
  • 2020-11-22 02:38

    You're right -- the purpose of try and except are not to cover your sloppy coding. That just leads to more sloppy coding.

    Exception handling should be used to handle exceptional circumstances (sloppy coding is not an exceptional circumstance). However, often, it is easy to predict which exceptional circumstances might happen. (e.g. a your program accepts user input and uses that to access a dictionary, but the user's input wasn't a key in the dictionary ...)

    0 讨论(0)
  • 2020-11-22 02:39

    Ask forgiveness not permission is meant to simplify code. It's meant for code to be written like this when there's a reasonable expectation that .bar might trigger an AttributeError.

     try:
         print foo.bar
     except AttributeError as e
         print "No Foo!" 
    

    Your code appears to both ask permission AND forgiveness :)

    The thing is, if you reasonably expect something to fail, use a try/catch. If you don't expect something to fail, and it fails anyway, well the exception that gets thrown becomes the equivalent of a failed assertion in other languages. You see where the unexpected exception is occurring and adjust your code/assumptions accordingly.

    0 讨论(0)
提交回复
热议问题