课时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/0 except: with open("d:/a.txt","a") as f: traceback.print_exc(file=f)
#测试traceback模块的使用 import traceback try: print("step1") num=1/0 except: traceback.print_exc() 执行结果: Traceback (most recent call last): File "F:/python/python_pycharm/class_test/lesson123.py", line 5, innum=1/0 ZeroDivisionError: division by zero step1 Process 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) 执行结果: 输入一个年龄:200 Traceback (most recent call last): File "F:/python/python_pycharm/class_test/lesson123.py", line 14, inraise AgeError(age) __main__.AgeError: 200年龄错误 Process finished with exit code 1
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)