代码之家  ›  专栏  ›  技术社区  ›  gwydion93

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

  •  0
  • gwydion93  · 技术社区  · 7 年前

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

     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 部分?

    1 回复  |  直到 7 年前
        1
  •  1
  •   nick    7 年前

    两者有什么区别 pass continue ?

    是一个no操作,它告诉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, 4,6 持续 print 指示,鉴于 通过 将继续正常执行循环。

    为什么上面的代码不起作用?

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