60 python - 異常處理中拋出異常

class Test(object):
    def __init__(self, switch):
        self.switch = switch #開關
    def calc(self, a, b):
        try:
            return a/b
        except Exception as result:
            if self.switch:
                print("捕獲開啓,已經捕獲到了異常,信息以下:")
                print(result)
            else:
                #從新拋出這個異常,此時就不會被這個異常處理給捕獲到,從而觸發默認的異常處理
                raise


a = Test(True)
a.calc(11,0)

print("----------------------華麗的分割線----------------")

a.switch = False
a.calc(11,0)

運行結果:
在這裏插入圖片描述ide

相關文章
相關標籤/搜索