这是一个由Celery在Django环境中运行的python脚本。我需要创建一个问题,其余的错误'并提出异常,以便Celery发送有关该例外的电子邮件。
这会是最好的方法吗?
for thread in thread_batch:
try:
obj = query_set.get(thread_id=thread['thread_id'])
for key, value in thread.iteritems():
setattr(obj, key, value)
obj.unanswered = True
except ThreadVault.DoesNotExist:
obj = ThreadVault(**thread)
except:
raise Exception("There has been a unknown error in the database")
obj.save()
答案 0 :(得分:1)
是的,空except
将捕获与ThreadVault.DoesNotExist
不同的任何异常(在本例中)。但是你可以多改进你的代码。
始终尝试在try
块中添加较少的代码。你的代码可能是:
for thread in thread_batch:
try:
obj = query_set.get(thread_id=thread['thread_id'])
except ThreadVault.DoesNotExist:
obj = ThreadVault(**thread)
except:
raise Exception("There has been a unknown error in the database")
else: # Note we add the else statement here.
for key, value in thread.iteritems():
setattr(obj, key, value)
obj.unanswered = True
# Since save function also hits the database
# it should be within a try block as well.
try:
obj.save()
except:
raise Exception("There has been a unknown error in the database")