我使用 pymongo python 模块工作 mongodb 数据库。我的代码中有一个函数,调用该函数时会更新集合中的记录,如下所示。
for record in coll.find(<some query here>):
#Code here
#...
#...
coll.update({ '_id' : record['_id'] },record)
现在,如果我将代码修改如下:
for record in coll.find(<some query here>):
try:
#Code here
#...
#...
coll.update({ '_id' : record['_id'] },record,safe=True)
except:
#Handle exception here
这是否意味着更新失败时会引发异常,或者不会引发异常并且更新只会跳过导致问题的记录?
请帮忙
谢谢
try
and except
永远不会引发异常。他们只是处理抛出的异常。
If update
失败时抛出异常,except
将处理异常,然后循环将继续(除非您使用raise
in the except
条款)。
If update
失败时不会抛出异常,而是返回None
(或类似的东西),而你want它抛出异常,你可以使用:
if coll.update(...) is None: # or whatever it returns on failure
raise ValueError # or your custom Exception subclass
请注意,您应该始终指定要捕获的异常,并且仅将要捕获它的代码行括起来try
,这样您就不会隐藏代码中的其他错误:
for record in coll.find(<some query here>):
#Code here
#...
#...
try:
coll.update({ '_id' : record['_id'] },record,safe=True)
except SpecificException:
#Handle exception here
except OtherSpecificException:
#Handle exception here
else:
#extra stuff to do if there was no exception
See the try陈述 http://docs.python.org/reference/compound_stmts.html#the-try-statement, 内置异常 http://docs.python.org/library/exceptions.html, and 错误和异常 http://docs.python.org/tutorial/errors.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)