title: how to close db connections in except clause
body: <p>originally, I didn't have a main() function. I just had a whole bunch of code in:</p>
  
  <pre><code>if __name__ == '__main__':
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>if __name__ == '__main__':
      try:
          main()
      except :
          print "Unexpected error:", sys.exc_info()[0]
          engine.close()
          db.close()
  </code></pre>
  
  <p>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?</p>
  
  <p>edit: 
  <a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow">very helpful article about with statements</a></p>