5 ms·
Not to counter your point, but I would like to quote from PEP8 here: Additionally, for all try/except clauses, limit the try clause to the absolute minimum amo
by smnrchrds 13y ago
Not to counter your point, but I would like to quote from PEP8 here:
Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.
Yes:
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
No:
try:
# Too broad!
return handle_value(collection[key])
except KeyError:
# Will also catch KeyError raised by handle_value()
return key_not_found(key)
- yetanotherphd 13y agoThese two comments together make a lot of sense. When your try block is a single lookup, you might as well use an if statement or get. However, when the 'absolute minimum' is nontrivial try/except is still a good option, e.g. try: name = employee['name'] first_name = name['first_name'] last_name = name['last_name'] except KeyError: print "Bad employee data" return