 <p>If <code>mdb.connect</code> errors, there's nothing to assign to <code>con</code>, so it doesn't get defined.</p> <p>Instead of <code>finally</code>, try using <code>else</code>, which is run only when there was no exception. <a href="http://docs.python.org/2/tutorial/errors.html#handling-exceptions" rel="nofollow">Docs</a></p> <pre><code>try: con = mdb.connect('localhost','jmtoung','','ptb_genetics') except mdb.Error as e: print "Error" sys.exit(1) else: # else instead of finally con.close() </code></pre>