繁体   English   中英

捕获异常后继续循环

[英]Continue for loop after caught Exception

我正在通过csv.DictReader读取一个大(2Gb)文件(重要的是)。 文件深处的某个地方存在编码问题,我收到了UnicodeDecodeError 查看错误消息,我看到错误是在我的for循环中的隐式__next__中引发的。

代码存根将查看以下内容:

import csv

with open("myfile.csv", newline="") as f:
    c = csv.DictReader(f)
    for line in c: # here the error is happening
       pass

我想使用try-except模式来捕获任何读取错误,记录一条有意义的消息并继续读取文件。

我怎么能做到这一点? 我不能在循环外使用continue (即在except块中),所以我想我需要重写for循环,以便不使用隐式形式而是显式形式,但由于我对 python 相当陌生,我不知道如何以最 Pythonic 的方式做到这一点。


要模拟错误,请查看以下玩具示例:

class MyIterator:
    def __init__(self, mclass):
        self._mclass = mclass
        self._index = 0

    def __next__(self):
        if self._index == 3:
            # simulate an error in a file read
            self._index += 1
            raise Exception("simulated error"
        elif self._index < 5:
            self._index += 1
            return self._index - 1
        # End of Iteration
        raise StopIteration


class MyClass:
    def __iter__(self):
        return MyIterator(self)

obj = MyClass()
try:
    for result in obj:
        print(result)
except Exception as e:
    print("Exception covered")
    ## does not work for obvious reasons:
    # continue

只是为了记录,而不是试图在next上捕获错误,您可以将errors参数传递给open ,这决定了如何处理编解码器错误。

将您的对象包装在一个 iter 中并在 while 循环中调用 next

done = False
obj = iter(MyClass())
while not done:
    try:
        data = next(obj)
    except StopIteration:
        done = True
    except Exception:
         print("process error here and continue")

你用的是什么python版本? 另外为什么不使用 yield (请参阅此处输入链接描述

您可以返回而不是加注。 如果您知道 type(variable) 是否为 Exception 您可以处理信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM