【问题标题】:Using multiple try: except to handle error does not work使用多次尝试:除了处理错误不起作用
【发布时间】:2026-02-16 14:25:01
【问题描述】:

我有一个我正在迭代的文件列表:

 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()

“通过”和“继续”有什么区别,为什么上面的代码不起作用?我需要在IOError 部分添加更多具体信息吗?

【问题讨论】:

    标签: python-2.7 try-catch continue


    【解决方案1】:

    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()
    

    【讨论】:

    • 好的,我发现我的主要问题是try-catch 中的exit()for 循环之外。它现在似乎工作正常。谢谢。