欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

2022.01.31

时间:2023-08-17

课时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 num=1/0ZeroDivisionError: division by zerostep1Process finished with exit code 0

课时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 raise AgeError(age)__main__.AgeError: 200年龄错误Process finished with exit code 1

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。