使用异常处理代码流的afaik是错误的。我正在编写一个名为getEntity(id)的方法的代码,当找不到实体时,getEntity抛出一个DoesNotExist异常。没有entityExists(id)方法。为了检查实体是否存在,代码通常会:
try:
getEntity(id)
catch DoesNotExist as e:
# entity does not exist
在我看来这会更好:
^{pr2}$这是常识吗?我认为代码是这样的,因为它使用Django,它复制了Django异常名(DoesNotExist)以及它处理实体不存在的常用方法。在
这个问题不是Python特有的,但是我作为例子使用的代码是Python的,因此我用Python标记了这个问题。在
依我看,这要看具体情况。如果你确实知道所有可能的结果,那么继续做If/else(LBYL)。如果您不确定可能的结果(例如,在处理未知类型的变量时),try/catch(EAFP)是一种更安全的方法。在
这被称为EAFP或比允许更容易请求原谅。从The Python Glossary:
LBYL意思是三思而后行。再次从The Python Glossary:
接下来,它将为您的
if not entityExists(id):
建议提供一个很好的反例:当你用Python语言写代码的时候,谁能帮助你更容易地阅读。在
相关问题 更多 >
编程相关推荐