In Python, you absolutely should catch and re-throw that exception, for the sole reason that a reader of the code immediately sees that it might raise during normal execution.
This tells a reader that the corresponding value is returned, but you haven't thought about the proper behaviour when the key is not found:
def get(key):
return items[key]
This tells me that you expect to be given missing keys, and that callers may receive a KeyError. A caller is expected to catch that error:
def get(key):
try:
return items[key]
except KeyError:
raise
This tells me that the key must be present, anything else would be a programming error:
def get(key):
assert key in items
return items[key]
If you create a custom error message, make sure that this message contains all information needed to fix and understand the problem. In particular, the error message should contain the missing key – use repr()
not str()
for this.
"item {!r} was not registered".format(key)
If formatting of the error message is expensive and the error message would be rarely read because it will be caught in most cases, you can create a custom exception to defer formatting until the error is displayed. You can still inherit from KeyError so that it can be caught without any changes:
class NotRegisteredError(KeyError):
def __init__(self, key):
super().__init__(key)
self.key = key
def __str__(self):
return "item {!r} was not registered".format(self.key)
examples
andsigns of effort to think about the problem
here.