为try...except...else...finallydefself_error(type_list):"""异常处理函数传入一个可迭代对象,当参数为passedin:paramtype_list:aniterableobject"""try:foriintype_list:print(i)except:print("Notaniterableobject")else:print("Noerroroccurred")finally:print("程序isfinished")self_error("abc")"""abc没有错误发生,程序结束"""self_error(2)"""不是可迭代对象程序结束"""从程序中可以看出也就是说,如果try部分执行顺利,就会执行else部分,如果try出现一些错误,就会执行except部分,但是这两种情况,最后都会输出finally部分。当然else和finally部分可以省略。我们可以自定义输出错误类型,需要用到raise函数。defself_error(type_num):"""Exceptionhandler自定义异常函数,用于抛出异常:paramtype_num:value用于判断是否抛出异常:返回异常信息"""iftype_num<10:raiseValueError("如果valueislessthan10")else:return200if__name__=="__main__":self_error(11)#200self_error(9)#ValueError:如果值小于10,抛出异常,只适用于python的标准异常class异常名称描述ArithmeticError所有数值计算错误的基类AssertionError断言语句失败AttributeError对象没有该属性BaseException所有异常的基类DeprecationWarning关于弃用特性的警告EnvironmentError操作系统错误的基类EOFError没有内置输入,达到EOFException一般错误FloatingPointError的基类浮点计算错误FutureWarning关于构造未来语义会改变的警告GeneratorExit生成器(generator)有异常通知退出KeyboardInterrupt用户中断执行(通常为^C类型)KeyErrorThekeyisnotpresentinthemappingfatal)NameErrorundeclared/initializedobject(hasnoattributes)NotImplementedErrormethodnotyetimplementedOSError操作系统错误OverflowError数值运算超出最大限制OverflowWarning旧警告auto-promotiontolongPendingDeprecationWarningaboutfeaturewillbedeprecated警告ReferenceErrorweakreference(Weakreference)AttempttoaccessanobjectthathasbeengarbagecollectedRuntimeErrorGeneralruntimeerrorRuntimeWarningSuspiciousruntimebehavior(运行时行为)警告StandardError所有内置标准异常的基类StopIterationIteratorhasnomorevaluesSyntaxErrorPythonSyntaxerrorSyntaxWarningSuspiciousSyntaxWarningSystemError一般解释器系统错误SystemExit解释器请求退出SystemExitPython解释器请求退出TabError制表符和空格混合类型错误对类型的无效操作UnboundLocalError访问UnicodeDecodeErrorUnicode解码错误UnicodeEncodeErrorUnicode编码错误UnicodeErrorUnicodeUnicode相关错误UnicodeTranslateErrorUnicode翻译错误UserWarning用户代码生成警告ValueError传递无效参数警告基类警告WindowsError系统调用失败ZeroDivisionError除以(或模)零(所有数据类型)
