当前位置: 首页 > 后端技术 > Python

Python:异常处理机制及常见异常类型

时间:2023-03-26 17:08:12 Python

Python的异常处理机制处理异常的几种代码结构:try...except...else结构如果try代码块中没有抛出异常,则执行else代码块,否则执行except代码块。graphTDA(try)-->|程序出现异常|B(except)A(try)-->|程序没有异常|C(else)try:n1=int(input('请输入一个整数:'))n2=int(input('请输入另一个整数:'))result=n1/n2exceptBaseExceptionase:print('代码错误')print(e)else:print('结果is:',result)try...except...else...finally结构如果try代码块中没有抛出异常,则执行else代码块,否则执行except代码块。finally代码块无论是否发生异常都会执行,常用于释放try块中请求的资源。graphTDA(try)-->|程序出现异常|B(except)A(try)-->|程序没有异常|C(else)B-->D{finally}C-->D{finally}try:n1=int(input('请输入一个整数:'))n2=int(input('请输入另一个整数:'))result=n1/n2exceptBaseExceptionase:print('代码错误')print(e)else:print('结果为:',result)finally:print('无论如何都会执行')print('程序结束')运行结果:请输入一个integer:1Pleaseenteranotherinteger:4ResultFor:0.25在任何情况下,程序都会被执行,使用traceback模块打印异常信息importtracebacktry:print('1.------------------')num=10/0except:traceback.print_exc()outputresult:Traceback(mostrecentcalllast):File"D:\study\python-study\chap8\traceback.py",行5、在num=10/0ZeroDivisionError:除以zeroPython中常见的异常类型ZeroDivisionError异常类型的简要说明除以(或取模)0(所有数据类型)IndexErrorTheindexwasnotfoundinthesequenceKeyErrorThekeywasnotfoundinthemapNameError未声明/初始化的对象(没有属性)SyntaxError语法错误ValueError传递的参数无效