[問題] 關於設計程式運作流程的問題
各位版友好,
最近在運用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
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
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
12/06 23:13, 3F
→
12/06 23:13,
5年前
, 4F
12/06 23:13, 4F
→
12/06 23:13,
5年前
, 5F
12/06 23:13, 5F
→
12/07 22:03,
5年前
, 6F
12/07 22:03, 6F
→
12/07 22:03,
5年前
, 7F
12/07 22:03, 7F
→
12/07 22:03,
5年前
, 8F
12/07 22:03, 8F
簡單來說應該是我try-except寫太多層吧?只要在最上層寫一個try-except就好了...感謝
各位的指導
※ 編輯: Dong0129 (118.167.123.168 臺灣), 12/08/2019 21:44:55
Python 近期熱門文章
PTT數位生活區 即時熱門文章