捕獲發生在 *loop 標頭而不是整個回圈或主體中的例外的最佳方法是什么。
舉個例子
for value in complex_generator(): # throws exceptions I might want to catch
... # do work here - but don't catch any exception
我認為沒有幫助的是將整個回圈包裝在 try 和 except 塊中,如下所示:
try:
for value in complex_generator(): # throws exceptions I might want to catch
... # exceptions raised here will also be caught :(
except Exception:
... # handle exception here
受 golang 的啟發,可能會封裝 try-except-block 并始終回傳兩個元素:
def wrapper(iterable):
try:
for value in iterable:
yield value, None
except Exception as e:
yield None, e
for value, err in wrapper(complex_generator()):
if err != None:
... # handle error
else:
... # do work but don't catch any exception here
然而,這并不像pythonic,型別檢查器也需要額外的檢查。有任何想法嗎?
uj5u.com熱心網友回復:
有兩個級別的錯誤:生成器拋出的錯誤,以及您的作業代碼拋出的錯誤。我會使用嵌套try:
try:
for value in complex_generator():
try:
# do work here
except ValueError:
# catch ValueError and keep going
except OtherError:
# catch OtherError and keep going
# any other error breaks the loop
except ExpectedGeneratorError:
# handle generator exception here
except:
# handle more errors
您可以將內部部分提取到作業函式中以保持整潔。
uj5u.com熱心網友回復:
先搞定發電機?
try:
cg = complex_generator()
except Exception as e:
cg = [] # could alternatively have a success boolean here, and wrap the `for` loop below in an `if`
for value in cg:
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/426267.html
標籤:Python python-3.x 例外
