1. 程式人生 > >Python中自定義異常與丟擲異常

Python中自定義異常與丟擲異常

# class ShortInputException(Exception):
#     def __init__(self,length,atleast):
#         super().__init__()
#         self.length = length
#         self.atleast = atleast
# def main():
#     try:
#         s = input("請輸入 -->")
#         if len(s)<3:
#             raise ShortInputException(len(s),3)
#     except ShortInputException as result:
#         print("ShortCutException:輸入的長度是%d,長度至少應該是 %d"%(result.length,result.atleast))
#     else:
#         print("沒有發生異常")
# main()

class tast(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:
                print("重新開啟異常捕獲。")
                raise
a = tast(True)
a.calc(11,0)
print("異常處理結束了。")
a.switch = False
a.calc(11,0)