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

yipeiwu_com6年前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如何为图片添加水印

添加水印的主要目的是为了版权保护,使自己的图像不被抄袭或者恶意转载。网上有很多制作水印的工具,本帖介绍怎么使用Python-Pillow库给图片添加水印。 使用ImageMagick添加...

django rest framework 数据的查找、过滤、排序的示例

django rest framework 数据的查找、过滤、排序的示例

对于管理系统,常常需要展示列表数据,我们对于列表内的数据常常需要查找、过滤、排序等操作,其中查找等操作大部分是在后台进行的。django rest framework可以轻松的实现数据的...

python科学计算之scipy——optimize用法

写在前面 SciPy的optimize模块提供了许多数值优化算法,下面对其中的一些记录。 非线性方程组求解 SciPy中对非线性方程组求解是fslove()函数,它的调用形式一般为fsl...

python判断一个集合是否包含了另外一个集合中所有项的方法

本文实例讲述了python判断一个集合是否包含了另外一个集合中所有项的方法。分享给大家供大家参考。具体如下: >>> L1 = [1, 2, 3, 3] >&...

python实现递归查找某个路径下所有文件中的中文字符

本文实例为大家分享了python实现递归查找某个路径下所有文件中的中文字符,供大家参考,具体内容如下 # -*- coding: utf-8 -*- # @ description:...