简体   繁体   English

在python中混淆异常行为

[英]confusing exception behavior in python

I have some django code that resembles this (this is python 2.7.1) 我有一些类似于这的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")

The problem is the "this should not print" line is still being printed. 问题是“这不应该打印”的行仍在打印中。 I'm confused by this. 我很困惑。 I feel like I am probably overlooking something very simple but might be having some tunnel vision at the moment. 我觉得我可能忽略了一些非常简单的事情,但目前可能有一些隧道视野。 Thanks in advance. 提前致谢。

Update: also if I remove the nested try block the print below the call to the method that throws an exception still prints. 更新:如果我删除嵌套的try块,则在调用抛出异常的方法下面的打印仍会打印。

I figured it out, the method had a try block inside of it that Iw asn't raising out. 我想通了,这个方法里面有一个尝试块,但我没有提高。 adding raise in my exception handler inside the method_that_throws_exception() fixed my problem. 在method_that_throws_exception()中的异常处理程序中添加raise修复了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM