知行编程网知行编程网  2022-12-04 04:00 知行编程网 隐藏边栏  1 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python中自定义异常的使用举例的相关知识,希望可以帮到处于编程学习途中的小伙伴

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

Python中使用自定义异常的例子

以下是与 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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享