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__)

猜你喜欢

转载自blog.csdn.net/weixin_42039090/article/details/80565636