How can I keep the try block as small as possible when I have to catch an exception which can occur in a generator?
A typical situation looks like this:
for i in g():
process(i)
If g() can raise an exception I need to catch, the first approach is this:
try:
for i in g():
process(i)
except SomeException as e:
pass # handle exception ...
But this will also catch the SomeException if it occurs in process(i) (this is what I do not want).
Is there a standard approach to handle this situation? Some kind of pattern?
What I am looking for would be something like this:
try:
for i in g():
except SomeException as e:
pass # handle exception ...
process(i)
(But this is syntactic nonsense of course.)
You could convert exceptions occurring in the inner block:
Another option is to write a local generator that wraps
g: