怎么解决Python中自定义异常-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

成都创新互联10多年成都企业网站定制服务;为您提供网站建设,网站制作,网页设计及高端网站定制服务,成都企业网站定制及推广,对隧道混凝土搅拌车等多个方面拥有丰富的网站推广经验的网站建设公司。

这篇文章将为大家详细讲解有关怎么解决Python中自定义异常,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

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

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

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

class Networkerror(RuntimeError):
  def __init__(self, arg):
   self.args = arg

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

try:
  raise Networkerror("Bad hostname")
except Networkerror,e:
  print e.args

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

>>> class MyError(Exception):
...   def __init__(self, value):
...     self.value = value
...   def __str__(self):
...     return repr(self.value)
...
>>> try:
...   raise MyError(2*2)
... except MyError as e:
...   print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError, 'oops!'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

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

我们通常定义的异常类,会让它比较简单,允许提取异常处理程序的错误信息,当创建一个异常模块的时候,常见的做法是创建一个由该模块定义的异常基类和子类,根据不同的错误条件,创建特定的异常类:

class Error(Exception):
  """Base class for exceptions in this module."""
  pass
 
class InputError(Error):
  """Exception raised for errors in the input.
 
  Attributes:
    expression -- input expression in which the error occurred
    message -- explanation of the error
  """
 
  def __init__(self, expression, message):
    self.expression = expression
    self.message = message
 
class TransitionError(Error):
  """Raised when an operation attempts a state transition that's not
  allowed.
 
  Attributes:
    previous -- state at beginning of transition
    next -- attempted new state
    message -- explanation of why the specific transition is not allowed
  """
 
  def __init__(self, previous, next, message):
    self.previous = previous
    self.next = next
    self.message = message

关于怎么解决Python中自定义异常就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

网站名称:怎么解决Python中自定义异常-创新互联
标题链接:https://www.cdcxhl.com/article8/epoip.html

成都网站建设公司_创新互联,为您提供关键词优化企业建站电子商务ChatGPT服务器托管标签优化

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

商城网站建设