Ramy
Ramy

Reputation: 21261

how to close db connections in except clause

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__ == '__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

Upvotes: 0

Views: 88

Answers (3)

Chris Pfohl
Chris Pfohl

Reputation: 19064

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.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799102

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

Upvotes: 4

Steven Rumbalski
Steven Rumbalski

Reputation: 45552

Put your exception handling inside main.

Upvotes: 3

Related Questions