使用 multiple try: except 来处理错误不起作用

Using multiple try: except to handle error does not work

我有一个正在遍历的文件列表:

 condition = True
 list = ['file1', 'file2', 'file3']
   for item in list:
     if condition == True      
        union = <insert process>
      ....a bunch of other stuff.....

假设代码在 file1 和 file3 上运行良好,但是当它到达 file2 时,抛出 IO 错误。我想要做的是在抛出 IOError 时绕过 file2 并返回列表中的下一项。我想使用 try: except 方法来执行此操作,但我似乎做不对。注意:我在代码开头有一个整体try-catch。我不确定它是否会干扰在代码的特定部分使用第二个。

try:
    try:
      condition = True
      list = ['file1', 'file2', 'file3']
      for item in list:
        if condition == True      
          union = <insert process>
      ....a bunch of other stuff.....

    except IOError:
      continue
    .....a bunch more stuff.....
except Exception as e:
    logfile.write(e.message)
    logfile.close()
    exit()

'pass' 和 'continue' 之间有什么区别,为什么上面的代码不起作用?我需要在 IOError 部分添加更具体的信息吗?

passcontinue有什么区别?

pass 是一个空操作,它告诉 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 块在循环外,一旦循环内发生异常,循环就会终止并跳转到 except 块外环形。要解决这个问题,只需将 tryexcept 块移动到 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()