Chinaunix首页 | 论坛 | 博客
  • 博客访问: 337617
  • 博文数量: 148
  • 博客积分: 2745
  • 博客等级: 少校
  • 技术积分: 1704
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-30 14:59
文章分类

全部博文(148)

文章存档

2013年(97)

2012年(7)

2011年(3)

2010年(41)

我的朋友

分类: Python/Ruby

2013-05-11 22:53:46

如果你需要,可以从Exception类派生。 在这个例子中,默认的__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 "", line 1in ?
__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
阅读(1019) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~