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
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