【问题标题】:Continue loop after exception is excepted排除异常后继续循环
【发布时间】:2015-08-19 05:35:47
【问题描述】:
我有一个带有try...except 的循环:
try:
for sqlcommand in sqlcommands:
cursor.execute(sqlcommand)
except psycopg2.ProgrammingError as err:
print "Programming error spotted. Message -->"
print err
此循环在 SQL 中创建表。但我想要的是如果已经有表(生成编程异常),打印异常下的消息但继续循环,而不是停止它。可以吗?
【问题讨论】:
标签:
python
sql
loops
exception
【解决方案1】:
你只需要改变try语句的顺序:
for sqlcommand in sqlcommands:
try:
cursor.execute(sqlcommand)
except psycopg2.ProgrammingError as err:
print "Programming error spotted. Message -->"
print err
在这种情况下,在迭代循环时,对于每个查询,try except 块将运行,如果发现错误,则主 for 循环迭代仍将工作。
【解决方案2】:
for sqlcommand in sqlcommands:
try:
cursor.execute(sqlcommand)
except psycopg2.ProgrammingError as err:
print "Programming error spotted. Message -->"
print err