[問題] __exit__ 怎麼 raise Exception?

看板Python作者 (ResolaQQ)時間9年前 (2016/01/19 19:09), 編輯推噓0(003)
留言3則, 2人參與, 最新討論串1/1
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

01/19 20:31, , 1F
如果裡面有 exception, exit 得到的三個參數會有值可以
01/19 20:31, 1F

01/19 20:32, , 2F
讓你 reraise, 優先處理它們就是了
01/19 20:32, 2F

01/19 21:12, , 3F
抱歉問了個蠢問題,從來沒用過那三個參數,就自動遺忘了
01/19 21:12, 3F
文章代碼(AID): #1MdXbUcf (Python)
文章代碼(AID): #1MdXbUcf (Python)