1. 程式人生 > >Python高手系列:自定義異常類(帶寫入日誌功能)

Python高手系列:自定義異常類(帶寫入日誌功能)



class MYException(Exception):
    def __init__(self,Message):
        Exception.__init__(self)
        self.__str__=Message
    def WriteLog(self,filename):
        import datetime
        with open("d:\\1.log",'a') as f:
            f.write(self.__str__+" "+"file:"+filename+" Time: "+\
                    datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        f.close()
try:
    x1=eval(input("please input 1st number:"))
    x2=eval(input("please input 2nd number:"))
    if x2>x1:
        raise MYException("第二數大於第一個數了,發生問題了")
except MYException as e:
    e.WriteLog(__file__)  #寫入到日誌中
    print(e.__str__)