【问题标题】:confusing exception behavior in pythonpython中令人困惑的异常行为
【发布时间】:2012-06-28 16:43:30
【问题描述】:

我有一些类似的 django 代码(这是 python 2.7.1)

try:
    a = some_model.objects.get(some_field='foo') #this could except if for some reason it doesn't exist
    method_that_throws_exception()    #it won't reach this if we get a DoesNotExist
except some_model.DoesNotExist:
    #if it doesn't exist create it then try again
    a = some_model.objects.create(....)
    try:
        method_that_throws_exception() #this time lets say another exception is raised by method
        print 'this should not print right?'
    except Exception as e:
        logging.error("error msg here")

问题是“这不应该打印”行仍在打印。我对此感到困惑。我觉得我可能忽略了一些非常简单的事情,但目前可能有一些隧道视野。提前致谢。

更新:如果我删除嵌套的 try 块,在调用引发异常的方法下方的打印仍然会打印。

【问题讨论】:

  • 如果该对象存在,您是否希望不处理您的方法引发的异常?

标签: python django exception exception-handling


【解决方案1】:

我想通了,这个方法里面有一个我不会提出来的 try 块。在 method_that_throws_exception() 内的异常处理程序中添加 raise 解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2011-11-09
    • 1970-01-01
    • 2012-09-22
    相关资源
    最近更新 更多