One important consideration when deciding whether to catch an exception is that you could hide legitimate errors.
For example, consider this code:
try: name = person['name'] except KeyError: name = '<none provided>'
This is reasonable if person
known as a dict
... But if person
can be something more complex, for example:
class Person(object): def __getitem__(self, key): return do_something(key)
You run the risk of accidentally catching an exception that was caused by a legitimate error (for example, an error in do_something
).
And I feel the need to mention: you should never, ever (with the exception of a few special circumstances) use "naked" except:
My personal preference is to avoid catching exceptions whenever possible (e.g. using name = person.get('name', '<none provided>')
), since I find it cleaner and I don't like it look of try / catch blocks.
source share