Python 2.7 使用多个try:except处理错误不起作用
我有一个正在迭代的文件列表:Python 2.7 使用多个try:except处理错误不起作用,python-2.7,try-catch,continue,Python 2.7,Try Catch,Continue,我有一个正在迭代的文件列表: condition = True list = ['file1', 'file2', 'file3'] for item in list: if condition == True union = <insert process> ....a bunch of other stuff..... “通过”和“继续”之间有什么区别?为什么上面的代码不起作用?我是否需要向IOError部分添加更具体
condition = True
list = ['file1', 'file2', 'file3']
for item in list:
if condition == True
union = <insert process>
....a bunch of other stuff.....
“通过”和“继续”之间有什么区别?为什么上面的代码不起作用?我是否需要向
IOError
部分添加更具体的信息?通过和继续之间有什么区别?
pass
是一个no-op,它告诉python什么也不做,直接转到下一条指令
continue
是一个循环操作,它告诉python忽略循环的这个迭代中剩下的任何代码,并简单地转到下一个迭代,就像它已经到达循环块的末尾一样
例如:
def foo():
for i in range(10):
if i == 5:
pass
print(i)
def bar():
for i in range(10):
if i == 5:
continue
print(i)
第一个将打印0,1,2,3,4,5,6,7,8,9,但第二个将打印0,1,2,3,4,6,7,8,9,因为continue
语句将使python跳回开始,而不是继续执行print
指令,而pass
将继续正常执行循环
为什么上述代码不起作用?
代码的问题是try
块在循环外部,一旦循环内部发生异常,循环将在该点终止并跳到循环外部的块。要解决此问题,只需将try
和except
块移动到for
循环中:
try:
condition = True
list = ['file1', 'file2', 'file3']
for item in list:
try:
# open the file 'item' somewhere here
if condition == True
union = <insert process>
....a bunch of other stuff.....
except IOError:
# this will now jump back to for item in list: and go to the next item
continue
.....a bunch more stuff.....
except Exception as e:
logfile.write(e.message)
logfile.close()
exit()
试试看:
条件=真
列表=['file1'、'file2'、'file3']
对于列表中的项目:
尝试:
#在此处某处打开文件“item”
如果条件==真
联合=
……一堆其他的东西。。。。。
除IOError外:
#现在将跳回列表中的项目:并转到下一个项目
持续
…更多的东西。。。。。
例外情况除外,如e:
logfile.write(e.message)
logfile.close()
退出()
OK,我发现我的主要问题是for
循环的try catch
外部的exit()
。现在看来还可以。谢谢
try:
condition = True
list = ['file1', 'file2', 'file3']
for item in list:
try:
# open the file 'item' somewhere here
if condition == True
union = <insert process>
....a bunch of other stuff.....
except IOError:
# this will now jump back to for item in list: and go to the next item
continue
.....a bunch more stuff.....
except Exception as e:
logfile.write(e.message)
logfile.close()
exit()