捕获状态中的异常

2024-10-03 06:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想捕获一个异常,它是由一个intestartor在迭代程序的循环之外的一个迭代中抛出的。你知道吗

这是一个非常简化的代码版本:

class C(object):
    def _iter(self):
        for x in range(100):
            yield x, x + 3

    def doit(self):
        for a, b in self._iter():    # <-- how can I capture an excepcion here?
            print(a, b)

我可以在迭代器循环中捕获异常,但是我如何将错误传递给doit方法进行报告呢?我想让异常一直传播到doit函数,在那里我可以收集错误并继续下一个元素。你知道吗

我还需要处理所有的迭代,收集错误,并处理所有的迭代没有错误,这样我就可以报告所有的错误在最后。这样,一个错误就不会阻止对所有其他元素的处理。你知道吗


Tags: 代码inself程序版本元素forobject
2条回答

这应该起作用:

class C(object):
    def _iter(self):
      try:  
          for x in range(100):
            yield x, x + 3
      except Exception as e:
          raise e

    def doit(self):
        try:
            for a, b in self._iter():    # <  how can I capture an excepcion here?
                print(a, b)
        except Exception as e:
            # do something with e
        # rest of the python code here

使用try-catch块。你知道吗

try:
  for a, b in self._iter():
    print(a, b)

except:
  #throw your exception text here

相关问题 更多 >