【发布时间】:2013-08-23 09:02:16
【问题描述】:
如果函数失败是正常的,例如在数据库中找不到记录或任何其他表明可能缺少值的情况,是否建议使用异常来处理这种情况?
示例伪代码:
function retrieve(foo):
results = db.query("SELECT * FROM bar WHERE foo="+foo)
if not results:
throw Exception("no results")
return results[0]
function main:
try:
record = retrieve(42)
except:
print "no record with 42"
.... will create the record and continue
else:
print "record found: "+record
.... will use the existing record and continue
另一种解决方案可能是返回空值而不是启动此异常。 哪一个最有可能成为反模式?哪些情况下最好使用异常,哪些情况下不可以?
【问题讨论】:
标签: coding-style scalability design-patterns anti-patterns