chink
chink

Reputation: 1643

Pass the exception and execute the next lines of code

I have a basic doubt in python about exceptions. I have written a code,part of it looks like which looks like

    try:
        if deviceType == 2:
            print('data recieved')
            a = payload[77000][2,39]
            a = a.item()            
            b = payload[77000][2,91]
            b = b.item()
            c = payload[77000][2,35]
            c = c.item()
            d = payload[77000][2,36]
            d = d.item()
            insert_tuple = (a,b,c,d)           
            cursor.execute(sql_insert_query,insert_tuple)
            connection.commit()
    except mysql.connector.Error as error:
        connection.rollback() #rollback if any exception occured
        print("Failed inserting record into python_users table {}".format(error))

so, for example if payload[77000][2,39] does not exist or undefined, it throws an exception of 'Key Error' and the other values also don't get inserted into db, So is there is way if its undefined I can assign it a null value or ''.

Thanks

Upvotes: 2

Views: 78

Answers (2)

N Chauhan
N Chauhan

Reputation: 3515

You can place your repeated lines into a loop:

if deviceType == 2:
  print('data received')
  insert = []
  for i in (39, 91, 35, 36):
    try:
      item = payload[77000][2, i].item()
    except KeyError:
      item = ''
    insert.append(item)

  insert = tuple(insert)

  try:
    cursor.execute(sql_insert_query, insert)
    connection.commit()
  except mysql.connection.Error as error:
    connection.rollback()
    print("Failed inserting record into python_users table {}".format(error))

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54223

Sounds like you're getting a KeyError, so catch for that! Try grabbing each payload first:

# gather your payloads
payload_slices = [
    slice(2, 39),
    slice(2, 91),
    slice(2, 35),
    slice(2, 36)
]

payloads = []
for sl in payload_slices:
    try:
        item = payload[77000][sl].item()
    except KeyError:
        # handle a single failed payload here
        pass
    else:
        payloads.append(item)

# insert
insert_tuple = tuple(payloads)
try:        
    cursor.execute(sql_insert_query,insert_tuple)
    connection.commit()
except mysql.connector.Error as error:
    connection.rollback() #rollback if any exception occured
    print("Failed inserting record into python_users table {}".format(error))

Upvotes: 2

Related Questions