看板 Python 關於我們 聯絡資訊
class A: def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): raise Exception('A') 在 __exit__ 一定會丟出 Exception 的情況下,底下這段的結果在預期之中 >>>> with A(): .... pass .... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "<stdin>", line 5, in __exit__ Exception: A 但底下這段就有問題了,先丟出的 Exception 被後丟出的覆蓋 >>>> with A(): .... raise Exception('B') .... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "<stdin>", line 5, in __exit__ Exception: A 請問該怎麼寫才能比較好處理這種情況? 我遇上 A, B, C 的 __exit__ 都有可能丟出 Exception 程式本體也有可能丟出 Exception,像這樣 >>> with A(), B(), C(): ... raise Exception('D') ... 結果一團亂,根本不知道要怎麼處理... -- 放著養蚊子的部落格 http://resolaqq.blogspot.tw -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.230.21.111 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1453201758.A.9A9.html
uranusjr: 如果裡面有 exception, exit 得到的三個參數會有值可以 01/19 20:31
uranusjr: 讓你 reraise, 優先處理它們就是了 01/19 20:32
ResolaQQ: 抱歉問了個蠢問題,從來沒用過那三個參數,就自動遺忘了 01/19 21:12