在生成器中捕获异常时保持try block较小

Alf*_*lfe 5 python exception generator except

当我必须捕获发生器中可能发生的异常时,如何保持try块尽可能小?

典型情况如下:

for i in g():
  process(i)
Run Code Online (Sandbox Code Playgroud)

如果g()可以引发我需要捕获的异常,第一种方法是:

try:
  for i in g():
    process(i)
except SomeException as e:
  pass  # handle exception ...
Run Code Online (Sandbox Code Playgroud)

但这也会发现SomeException它是否发生process(i)(这是我不想要的).

有没有一种标准方法来处理这种情况?某种模式?

我正在寻找的是这样的:

try:

  for i in g():

except SomeException as e:
  pass  # handle exception ...

    process(i)
Run Code Online (Sandbox Code Playgroud)

(但这当然是语法上的废话.)

eca*_*mur 3

您可以转换内部块中发生的异常:

class InnerException(Exception):
  pass

try:
  for i in g():
    try:
      process(i)
    except Exception as ex:
      raise InnerException(ex)
except InnerException as ex:
  raise ex.args[0]
except SomeException as e:
  pass  # handle exception ...
Run Code Online (Sandbox Code Playgroud)

另一种选择是编写一个本地生成器来包装g

def safe_g():
  try:
    for i in g():
      yield i
  except SomeException as e:
    pass  # handle exception ...
for i in safe_g():
  process(i)
Run Code Online (Sandbox Code Playgroud)