课时131
#测试with上下文管理(with不是用来取代try……except……finally结构的,只是作为补偿,#方便我们在文件管理,网络通讯时的开发。with open("F:/nlp相关/代词.txt","r") as f: content=f.readline() print(content)print("程序结束!")执行结果:敝人程序结束!Process finished with exit code 0
课时132
##将异常信息输出到指定文件夹中try: print("step2") num=1/0except: with open("d:/a.txt","a") as f: traceback.print_exc(file=f)
#测试traceback模块的使用import tracebacktry: print("step1") num=1/0except: traceback.print_exc()执行结果:Traceback (most recent call last): File "F:/python/python_pycharm/class_test/lesson123.py", line 5, in
课时133
#自定义异常类class AgeError(Exception):#继承exception类 def __init__(self,errorinfo): Exception.__init__(self) self.errorinfo=errorinfo def __str__(self): return str(self.errorinfo)+ "年龄错误"####测试代码####if __name__=="__main__": #如果是为True,则模块是作为独立文件运行,可以执行测试代码 age=int(input("输入一个年龄:")) if age<1 or age>150: raise AgeError(age) else: print("正常的年龄:",age)执行结果:输入一个年龄:200Traceback (most recent call last): File "F:/python/python_pycharm/class_test/lesson123.py", line 14, in