详解在Python程序中自定义异常的方法

yipeiwu_com5年前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中logging实例讲解

Python中logging实例讲解

logging 的基本用法网上很多,这里就不介绍了。在引入正文之前,先来看一个需求: 假设需要将某功能封装成类库供他人使用,如何处理类库中的日志? 数年前在一个 C# 开发的项目中,我用...

python使用opencv驱动摄像头的方法

如下所示: #coding:utf-8 import cv2 import sys from PIL import Image def CatchUsbVideo(win...

深入理解python中的atexit模块

atexit 模块介绍 python atexit 模块定义了一个 register 函数,用于在 python 解释器中注册一个退出函数,这个函数在解释器正常终止时自动执行,一般用来...

PyTorch学习:动态图和静态图的例子

动态图和静态图 目前神经网络框架分为静态图框架和动态图框架,PyTorch 和 TensorFlow、Caffe 等框架最大的区别就是他们拥有不同的计算图表现形式。 TensorFlow...

python各层级目录下import方法代码实例

这篇文章主要介绍了python各层级目录下import方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 以前经常使用pyth...