python - Python中的自定义异常似乎不遵循 "its easier to ask for forgiveness"?

标签 python python-3.x exception error-handling

我正在尝试改进我的编码,最近遇到了自定义异常和“请求宽恕比请求更容易”(EAFP)的概念,但在我看来,自定义异常仍然遵循这个概念。

例如,在下面的代码中,A 看起来很干净,但没有自定义异常。 B 看起来也很干净,但没有自定义异常,并且不遵循 EAFP 概念。 B 的替代方法是将 KeyError 替换为自定义错误。 C 有一个自定义异常,但它看起来相当冗长,对我来说,它几乎看起来更接近 LBYL。

示例 C 通常是如何使用自定义异常的? (使用 try/except 和 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)

最佳答案

在这种情况下,您应该使用自定义异常向通用 KeyError 异常添加详细信息。您可以在异常处理 block 中使用 from 关键字将异常与基本异常关联起来,如下所示:

class AnimalNotFoundError(KeyError):
    pass

try:
    # Don't look, just take
    animal_type = animal_dict['hamster']
except KeyError as ex:
    # Add some detail for the error here, and don't silently consume the error
    raise AnimalNotFoundError('Invalid animal: {}'.format('hamster')) from ex

关于python - Python中的自定义异常似乎不遵循 "its easier to ask for forgiveness"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61309359/

相关文章:

python - 带有 Pandas 的 DataFrame 的 DataFrame

Python/SciPy : How to get cubic spline equations from CubicSpline

c++ - 我应该使用 __throw_logic_error 吗?

python - 避免 Python 中的多个 Try/Except block

Java 异常处理 Do 循环不起作用?

python - 缩进包裹的、带括号的 if 条件时的样式

python Pandas : How to skip columns when reading a file?

python - Python 3.x 中字符串的内部表示是什么

python - 将解析数字格式化为 float()

python-3.x - 如何为 BigQuery 的 Google Cloud 远程实例提供身份验证?