简体   繁体   中英

Continue loop after exception is excepted

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM