https://www.cnblogs.com/zhangyin6985/p/7229553.html
當程序出現錯誤,python會自動引發異常,也可以通過raise顯示地引發異常。一旦執行了raise語句,raise后面的語句將不能執行。
演示raise用法
try:
s = None
if s is None:
print "s 是空對象"
raise NameError #如果引發NameError異常,后面的代碼將不能執行
print len(s) #這句不會執行,但是后面的except還是會走到
except TypeError:
print "空對象沒有長度"
s = None
if s is None:
raise NameError
print 'is here?' #如果不使用try......except這種形式,那么直接拋出異常,不會執行到這里
#coding:utf-8 class NameNotFound(Exception): def __init__(self): print "名字沒有發現異常" pass def test(x): if x==0: raise NameNotFound print "hello" try: test(0) except NameNotFound: print NameNotFound.message pass