Python Exceptions: EAFP and What is Really Exceptional?

前端 未结 5 2081
情话喂你
情话喂你 2020-12-02 21:37

It\'s been said in a couple places (here and here) that Python\'s emphasis on \"it\'s easier to ask for forgiveness than permission\" (EAFP) should be tempered with the idea

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 21:53

    I've found the practice of using exceptions as "normal" flow control tools to be a fairly widely accepted in Python. It's most commonly used in situations like the one you describe, when you get to the end of some sort of sequence.

    In my opinion, that's a perfectly valid use of an exception. You do want to be careful about using exception handling willy-nilly though. Raising an exception is a reasonably expensive operation, and therefore it's best to ensure you only rely on an exception at the end of the sequence, not in each iteration.

提交回复
热议问题