开发者

how to close db connections in except clause

开发者 https://www.devze.com 2023-02-13 01:16 出处:网络
originally, I didn\'t have a main() function. I just had a whole bunch of code in: if __name__ == \'__main__\':

originally, I didn't have a main() function. I just had a whole bunch of code in:

if __name__ == '__main__':

I'm trying to refactor the code a bit so that it's a little cleaner and does come clean up in case the code raises an exception. So, now my code looks like this:

if __name__开发者_如何学JAVA == '__main__':
    try:
        main()
    except :
        print "Unexpected error:", sys.exc_info()[0]
        engine.close()
        db.close()

the problem is, engine and db are both created inside of main(), so I don't really have a reference to them. Is there a way to handle the exception in this way, or do I have to make it more granular within the main() function?

edit: very helpful article about with statements


Use either the with statement with an appropriate context manager or try ... finally to make sure that your connections are closed.


Put your exception handling inside main.


The other answers really are much better, but you can also pass data inside Exception objects if you raise them yourself or catch them, modify them, and re-raise them.

It's a much better practice to catch and handle your exceptions so that exceptions coming out of main are truly exceptional.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号