Using try vs if in python

后端 未结 9 1108
终归单人心
终归单人心 2020-11-22 12:59

Is there a rationale to decide which one of try or if constructs to use, when testing variable to have a value?

For example, there is a f

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 13:29

    Generally, the impression I've gotten is that exceptions should be reserved for exceptional circumstances. If the result is expected never to be empty (but might be, if, for instance, a disk crashed, etc), the second approach makes sense. If, on the other hand, an empty result is perfectly reasonable under normal conditions, testing for it with an if statement makes more sense.

    I had in mind the (more common) scenario:

    # keep access counts for different files
    file_counts={}
    ...
    # got a filename somehow
    if filename not in file_counts:
        file_counts[filename]=0
    file_counts[filename]+=1
    

    instead of the equivalent:

    ...
    try:
        file_counts[filename]+=1
    except KeyError:
        file_counts[filename]=1
    

提交回复
热议问题