[問題] 關於設計程式運作流程的問題

看板Python作者 (阿東)時間5年前 (2019/12/06 17:21), 5年前編輯推噓2(206)
留言8則, 3人參與, 5年前最新討論串1/1
各位版友好, 最近在運用exception時遇到一個流程設計的問題, 假設我有3個函式,分別是a、b、c, 其中a會呼叫b和c,b會呼叫c 若是想做到只要有函式出現例外,整個程式就停止運作, 是否只能用判斷式一一檢查執行完的函式是否正常跑完呢? 還是有其他種作法呢? 如果只能用判斷式一一檢查被呼叫的函式執行結果,若a大量呼叫b和c,不就會充斥很多 判斷式在a中嗎? 附上範例... #main.py from test import test if __name__=='__main__': t=test() t.test() ------------------------------------------------------------ #test.py from ErrManager import ErrManager from test2 import test2 class test: def test(self): try: print("test:test2 begin") t2=test2() t2.test2() print("test:test2 end") except ErrManager as e: print(e) ------------------------------------------------------------ #test2.py from ErrManager import ErrManager from test3 import test3 class test2: def test2(self): try: print("test2:test3 begin") t3=test3() t3.test3() print("tes2:test3 end") raise ErrManager("Exception in test2") except ErrManager as e: print(e) ------------------------------------------------------------- #test3.py from ErrManager import ErrManager class test3: def test3(self): try: raise ErrManager("Exception in test3") except ErrManager as e: print(e) ------------------------------------------------------------- #ErrManager class ErrManager(Exception): def __init__(self,arg): self.arg=arg ------------------------------------------------------------- 我以為運作結果會印出 test:test2 begin test2:test3 begin Exception in test3 但實際上印出 test:test2 begin test2:test3 begin Exception in test3 tes2:test3 end Exception in test2 test:test2 end 請問是我運用Exception的方式有錯嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.137.25.175 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1575624119.A.9D8.html ※ 編輯: Dong0129 (114.137.25.175 臺灣), 12/06/2019 17:22:39

12/06 17:37, 5年前 , 1F
你可以把try except寫在b, c裡面
12/06 17:37, 1F
有的,設計上每個function都有自己的try-except, 但被呼叫的函式執行發生exception後,在呼叫的地方還是要檢查一次才會停止運作... ※ 編輯: Dong0129 (114.137.25.175 臺灣), 12/06/2019 17:49:30

12/06 19:43, 5年前 , 2F
如果要中斷,何不raise error?
12/06 19:43, 2F
有的,我是使用自定義的例外,文末附上範例代碼...若我對於Exception運用理解錯誤還 請提出指教。 ※ 編輯: Dong0129 (220.137.94.193 臺灣), 12/06/2019 22:19:21 ※ 編輯: Dong0129 (220.137.94.193 臺灣), 12/06/2019 22:19:54 ※ 編輯: Dong0129 (220.137.94.193 臺灣), 12/06/2019 22:23:17

12/06 23:13, 5年前 , 3F
因為你 except 把例外攔下來了,想讓它向外傳播的話
12/06 23:13, 3F

12/06 23:13, 5年前 , 4F
在最外層或你想處理例外的地方 try except 就好
12/06 23:13, 4F

12/06 23:13, 5年前 , 5F
如果想在中間做些 logging 可以先攔下來再 re-raise
12/06 23:13, 5F

12/07 22:03, 5年前 , 6F
按照你的寫法,印出來的確實是會這樣沒錯。如果真的
12/07 22:03, 6F

12/07 22:03, 5年前 , 7F
想中斷又不大改的話就是直接在test3裡面把except裡的p
12/07 22:03, 7F

12/07 22:03, 5年前 , 8F
rint(e)改成raise e
12/07 22:03, 8F
簡單來說應該是我try-except寫太多層吧?只要在最上層寫一個try-except就好了...感謝 各位的指導 ※ 編輯: Dong0129 (118.167.123.168 臺灣), 12/08/2019 21:44:55
文章代碼(AID): #1TwXstdO (Python)
文章代碼(AID): #1TwXstdO (Python)