位置:- 正文

Python中自定义异常的使用举例(Python中自定义异常)

编辑:rootadmin

推荐整理分享Python中自定义异常的使用举例(Python中自定义异常),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:python自定义异常值替换,Python中自定义异常,python自定义异常代码,python中自定义异常需要继承什么类,Python中自定义异常,python自定义异常,python自定义异常处理,python自定义异常,内容如对您有帮助,希望把文章链接给更多的朋友!

通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。

Python中自定义异常的使用举例(Python中自定义异常)

以下为与RuntimeError相关的实例,实例中创建了一个类,基类为RuntimeError,用于在异常触发时输出更多的信息。

在try语句块中,用户自定义的异常后执行except块语句,变量 e 是用于创建Networkerror类的实例。

classNetworkerror(RuntimeError):def__init__(self,arg):self.args=arg

在你定义以上类后,你可以触发该异常,如下所示:

try:raiseNetworkerror("Badhostname")exceptNetworkerror,e:printe.args

在下面这个例子中,默认的__init__()异常已被我们重写。

>>>classMyError(Exception):...def__init__(self,value):...self.value=value...def__str__(self):...returnrepr(self.value)...>>>try:...raiseMyError(2*2)...exceptMyErrorase:...print'Myexceptionoccurred,value:',e.value...Myexceptionoccurred,value:4>>>raiseMyError,'oops!'Traceback(mostrecentcalllast):File"<stdin>",line1,in?__main__.MyError:'oops!'

常见的做法是创建一个由该模块定义的异常基类和子类,创建特定的异常类不同的错误条件。

classError(Exception):"""Baseclassforexceptionsinthismodule."""passclassInputError(Error):"""Exceptionraisedforerrorsintheinput.Attributes:expression--inputexpressioninwhichtheerroroccurredmessage--explanationoftheerror"""def__init__(self,expression,message):self.expression=expressionself.message=messageclassTransitionError(Error):"""Raisedwhenanoperationattemptsastatetransitionthat'snotallowed.Attributes:previous--stateatbeginningoftransitionnext--attemptednewstatemessage--explanationofwhythespecifictransitionisnotallowed"""def__init__(self,previous,next,message):self.previous=previousself.next=nextself.message=message
本文链接地址:https://www.jiuchutong.com/zhishi/310701.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/310702.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络