Python泛型异常来捕获其余错误

2024-10-02 02:42:28 发布

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

这是一个在Django环境中运行的python脚本。我需要创建一个捕获'其余的错误',并提出一个例外,以便芹菜将发送一个电子邮件的例外。在

这是最好的办法吗?在

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()

Tags: djangokeyin脚本idobjforvalue
1条回答
网友
1楼 · 发布于 2024-10-02 02:42:28

是的,空的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")

相关问题 更多 >

    热门问题