異常是指當程序語法正確,但運行的時候依舊發生的錯誤咱們稱之爲異常。
異常通常不會被程序處理,都已錯誤信息的形式表現出來。html
try: # 程序正常執行的代碼 a = os.listdir() except: # 發生異常時執行的代碼 print('發生異常')
發生異常
執行步驟:python
注意:函數
try: # 正常執行的代碼 a = 3 b = 4 c = a/b except: # 發生異常時執行的代碼 print('發生異常') else: # 沒有發生異常時執行的代碼 print('{0}/{1}={2}'.format(a,b,c))
3/4=0.75
try: # 正常執行的代碼 a = 3 b = 4 c = a/b d = 10 e = d/0 except: # 發生異常時執行的代碼 print('發生異常') else: # 沒有發生異常時執行的代碼 print('{0}/{1}={2}'.format(a,b,c)) finally: print('d*c={0}'.format(c*d))
發生異常 d*c=7.5
Python 使用 raise 語句拋出一個指定的異常。code
raise語法格式orm
raise [Exception [, args [, traceback]]]htm
a = 0 if a == 0: raise Exception('b/a中除數a爲0因此拋出異常')
--------------------------------------------------------------------------- Exception Traceback (most recent call last) <ipython-input-4-f517360799a9> in <module> 1 a = 0 2 if a == 0: ----> 3 raise Exception('b/a中除數a爲0因此拋出異常') Exception: b/a中除數a爲0因此拋出異常
斷言(assert)blog