Python中的自定义异常似乎没有遵循“请求原谅更容易”的原则?

2024-10-01 17:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力改进我的编码,最近遇到了自定义异常和“请求原谅比请求许可更容易”(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)

Tags: 代码概念示例iftypeelsedicttry
1条回答
网友
1楼 · 发布于 2024-10-01 17:22:48

在这种情况下,您应该使用自定义异常向泛型KeyError异常添加详细信息。您可以在异常处理块中使用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

相关问题 更多 >

    热门问题