try: raise #抛出一个异常 print "ok" except IOError,e : #捕获io异常,e是异常实例 print(e) except (IOError,ValueError),e : #捕获io异常 或者 错误值异常,e是异常实例 print(e) except: print ("Unexpected error") #捕获其他异常 else: #没有异常发生时调用 print "no Exception" finally: # 总是会被调用 print "finally,always running"
def a(): try: b() except: print ("error,a") else: print "ok.a" finally: print "finally,a" def b(): try: c() except: print ("error,b") else: print "ok,b" finally: print "finally,b" def c(): raise Exception a() 结果: error,b #捕获错误b finally,b #执行finally ok,a #因为异常在b函数中已经处理,所以a函数中没有捕获到异常 finally,a #处理函数a中的finally
bad=‘error’ #自定义一个字符串异常 class bad(Excepotin):pass #自定义一个类异常,继承Exception try raise bad catch bad: print "bae"
语法:assert boolean , 'str'
a = 1 b = 2 assert a > b,'a is smaller than b'
作用:当boolean为假时,打印str。assert会抛出异常并停止执行
断言长用于检测环境变量,约束等