try: s = None if s is None: print "s 是空对象" raise NameError #如果引发NameError异常,后面的代码将不能执行 print len(s) except TypeError: print "空对象没有长度"
from __future__ import division class DivisionException(Exception): def __init__(self, x, y): Exception.__init__ (self, x, y) #调用基类的__init__进行初始化 self.x = x self.y = y if __name__ == "__main__": try: x = 3 y = 2 if x % y > 0 : #如果大于0, 则不能被初始化,抛出异常 print x/y raise DivisionException(x, y) except DivisionException,div: #div 表示DivisionException的实例对象 print "DivisionExcetion: x/y = %.2f" % (div.x/div.y)
运行结果:
1.5
DivisionExcetion: x/y = 1.50
python Exception中的raise、assert
原文:http://www.cnblogs.com/ouyxy/p/6082769.html