使用异常来控制代码

2024-09-28 20:54:06 发布

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

使用异常处理代码流的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标记了这个问题。在


Tags: django方法代码实体idas错误entity
2条回答

依我看,这要看具体情况。如果你确实知道所有可能的结果,那么继续做If/else(LBYL)。如果您不确定可能的结果(例如,在处理未知类型的变量时),try/catch(EAFP)是一种更安全的方法。在

这被称为EAFP比允许更容易请求原谅。从The Python Glossary

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as .

LBYL意思是三思而后行。再次从The Python Glossary

This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

接下来,它将为您的if not entityExists(id):建议提供一个很好的反例:

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.

当你用Python语言写代码的时候,谁能帮助你更容易地阅读。在

相关问题 更多 >