Search code examples
pythonincrementbehaviorexceptdecrement

python unclear behavior when decrementing in try-except


Is there any special behavior when decrementing a variable in the except clause? sid keeps incrementing until it first gets into the exception clause, then it just keeps the same value for the rest duration of the for loop.

7 out of 105 tries throw an exception

there is no printout "Fehlercode:", errorcode

Here's my code:

for bid in range(bidStart, bidEnd + 1):
    for syn in getSynsProBeitrag(bid):
        try:
            sid += 1
            query = "INSERT INTO zuord (bid, hid, sid) VALUES(%s, %s, %s)"
            cursor.execute(query, [bid, hid, sid])
            query2 = "INSERT INTO synonyme (synonym) VALUE (%s)"
            cursor.execute(query2, syn)

        except MySQLdb.IntegrityError, message:
            errorcode = message[0]      
            if errorcode == 1062:       
                sid -= 1
                print sid
            else:
                print "Fehlercode:", errorcode

solved: after the query2 throws it's first exception the first query is causing also an (the same) IntegrityError and then it just goes back and forth like colleen said


Solution

  • Well you're decrementing it in the except clause, and then incrementing it in the try, so it's just going back and forth.... if it fails the first time, it's going to keep failing.

    e.g.

    try:
    1
    try:
    1+1=2 ->fail->id-1=1
    try:
    1+1=2 ->fail->id-1=1
    try:
    1+1=2 ->fail->id-1=1
    try:
    1+1=2 ->fail->id-1=1
    ....
    

    etc.

    If you're trying to skip the id that failed, don't decrement it.