Python Beginner: How to prevent the execution of "finally"?

Function 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()

I understand that in an attempt ... except ... finally, the finally block will always be executed. In the above code, I do not want to finally execute in the second try block if there is an exception in the first try block. What am I doing wrong?

(Note: using python 2.4)

Clarification: I do not know whether MySQLdb will automatically close connections when an error occurs. The problem I encountered with the above code is when an error occurs while establishing a connection (the first try code block), calling dbi.close () in the finally block raises "AttributeError: the NoneType object does not have a close attribute with link to dbi ...

Solution : This worked as desired -

# define at the start 
dbi = None
sql = None

In the finally block

if sql is not None:
    sql.close()
if dbi is not None:
    dbi.close()

, . - . ( :).

+3
3

, , .

, try .

, . . . , , , , . , , , , .

+5

else: finally:. . :

try ... except else, , , . , , try .

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()

.. :

try:
    [code that might error]
except IOError:
    [This code is only ran when IOError is raised]
else:
    [This code is only ran when NO exception is raised]
finally:
    [This code is always run, both if an exception is raised or not]
+6

. , , , .

- "finally" "try". , , , , , .

EDIT:

, "finally". , , .

+4

Source: https://habr.com/ru/post/1706638/


All Articles