Python Beginner: How to Prevent 'finally' from executing?
<p>The function code:</p>

<pre><code># Connect to the DB
try:
    dbi = MySQLdb.connect(host='localhost', \
                          user='user', \
                          passwd='pass', \
                          db='dbname', \
                          port=3309)

    print "Connected to DB ..."

except MySQLdb.Error, e:
    apiErr = 2
    apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
    return

    # To prevent try..finally bug in python2.4,
    # one has to nest the "try: except:" part. 
try:
    try:
        sql = dbi.cursor()
        sql.execute("""
        SELECT *
        FROM table
        WHERE idClient =  %s
        """, (key, ))

        access = sql.fetchall()

        # [some more code here]           

    except MySQLdb.Error, e:
        apiErr = 2
        apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
        return

finally:
    sql.close()
    dbi.close()
</code></pre>

<p>I understand that in a try .. except .. finally, the finally block will always execute.
In the above code, I don't want the finally in the second try block to execute if there is an exception in the first try block. What am I doing wrong?</p>

<p>(Note: Using python 2.4)</p>

<p>Clarification: I am not aware if MySQLdb closes connections automatically when an error occurs. The problem I am facing with the above code is, when there is an error in establishing a connection (the first try block of the code), calling dbi.close() in the finally block raises "AttributeError: 'NoneType' object has no attribute 'close'" with reference to dbi ... </p>

<p><strong>Solution</strong>: 
This worked as desired -</p>

<pre><code># define at the start 
dbi = None
sql = None
</code></pre>

<p>In the finally block, </p>

<pre><code>if sql is not None:
    sql.close()
if dbi is not None:
    dbi.close()
</code></pre>

<p>Thanks to those who replied. I learned something new from all of you. (I'll try to phrase my questions more clearly the next time :).</p>
