python通過自訂異常,提前退出方法

來源:互聯網
上載者:User

標籤:通過   pytho   功能   異常   cas   簡化   size   需要   返回   

python退出的操作,搜尋後都是return、exit()等return:退出一個方法,並返回一個值exit():退出python  想要實現的功能:方法A中調用多個方法,方法B、方法C...,方法B有一個開關,是否結束方法A。如果標記結束就直接退出方法A,繼續執行其他的方法。 總的過程如下:print(“執行A之前的方法")def A():     B(isfinished=“true")     C()print(“方法A結束了,但是這句還要執行")  問題:可以這麼實現:print(“執行A之前的方法")def A():     B()     return     C()print(“方法A結束了,但是這句還要執行") 或者這麼實現:print(“執行A之前的方法")def A():     B(isfinished=“true")     if isfinished==“true”:          return     C()print(“方法A結束了,但是這句還要執行") 但是第一種需要每次都手動改代碼,第二種方法要加很多冗餘代碼(我有很多方法需要用isfinished來做開關),但是我只想通過開關isfinished來判斷是否退出A()  解決方案:通過B()中拋出一個異常,然後提前結束方法A  第一步:自訂一個異常,繼承Exception即可class FinishedException(Exception):
    def __init__(self,value):            self.value=value(如果不用記錄參數,就不需要寫value等)  第二步:通過raise拋出異常,外層方法catch住這個異常即可try:    raise FinishedException( “這個方法給出異常")except FinishedException as e:    print(e)  第三步:通過裝飾器統一對異常進行處理,簡化代碼def wrapper(func):    def _func(*args):
        try:
            func(*args)
        except FinishedException as e:
            print("[",e,"]為最後一個要執行的case,不執行接下來的操作,退出當前流程")
        except Exception as e:
            print("用例出錯:",e)
    return _funcdef wrapper_basecase(isfinished= “false")def _func(*args):     if isfinished == "true":     raise FinishedException(name)  使用裝飾器+異常的例子:@wrapper def A(driver,iteration=2):    @wrapper_basecase(isfinished="true")    def B():
        return xxx    B()   

python通過自訂異常,提前退出方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.