简体   繁体   中英

confusing exception behavior in python

I have some django code that resembles this (this is 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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