【发布时间】:2020-08-02 04:22:19
【问题描述】:
我正在尝试改进我的编码,最近遇到了自定义异常和“请求宽恕比许可更容易”(EAFP)的概念,但在我看来,自定义异常仍然遵循这个概念。
例如,在下面的代码中,A 看起来很干净,但没有自定义异常。 B 看起来也很干净,但没有自定义异常,并且不遵循 EAFP 概念。 B 的替代方法是将 KeyError 替换为自定义错误。 C 有一个自定义异常,但它看起来很冗长,对我来说,它似乎更接近 LBYL。
示例 C 通常如何使用自定义异常? (使用 try/except AND if/else)
对于许多人将使用的生产级代码,示例 C 中的额外代码行是否值得?
animal_dict={'cat':'mammal',
'dog':'mammal',
'lizard':'reptile'}
# A - easier to ask for forgiveness not permission (EAFP)
try:
animal_type = animal_dict['hamster']
except KeyError:
print('Your animal cannot be found')
#B - look before you leap (LBYL)
if 'hamster' in animal_dict:
animal_type = animal_dict['hamster']
else:
raise KeyError('Your animal cannot be found')
# C - with custom exception
class AnimalNotFoundError(KeyError):
pass
try:
if 'hamster' in animal_dict:
animal_type = animal_dict['hamster']
else:
raise AnimalNotFoundError('Invalid animal: {}'.format('hamster'))
except AnimalNotFoundError as e:
print(e)
【问题讨论】:
-
不过,您永远不会仅仅为了在同一个代码块中捕获而引发异常。
-
不正确。我经常发现在单元测试中捕获 AssertionError 很方便,做一些事情(记录?检查?)然后将其重新启动。没错,我并没有含蓄地提出它,但我可能有理由在其他地方提出。
-
对于许多人将使用的生产级代码,示例 C 中的额外代码行是否值得? 这实际上取决于代码库的复杂性以及您想要的方式处理异常。
标签: python python-3.x exception error-handling