Continuing the loop after the exception is excepted

advertisements

I have a loop with a try...except:

try:
    for sqlcommand in sqlcommands:
        cursor.execute(sqlcommand)
except psycopg2.ProgrammingError as err:
    print "Programming error spotted. Message -->"
    print err

This loop creates tables in SQL. But I want here is if there is already table(Programming exception is generated), print the message under exception but continue loop, not stop it. Can I do it?


You simply need to change the order of try statement:

for sqlcommand in sqlcommands:
    try:
        cursor.execute(sqlcommand)
    except psycopg2.ProgrammingError as err:
        print "Programming error spotted. Message -->"
        print err

In this case while iterating the loop, for each query the try except block will run and if error is found the main for loop iteration would still be working.