
程序在運行的過程中總是會遇到各種各樣的問題,有一部分是 BUG,另外一部分我們稱之為異常(或錯誤)。大多數(shù)編程語言均使用以下語句來處理異常,Python 也不例外。
try:
pass
except:
pass
finally:
pass
先來看一個最簡單的處理異常的示例
#!/usr/bin/evn python3
# -*- coding:utf-8 -*-
try:
r = 1 / 0
except:
print('except')
以上代碼執(zhí)行結(jié)果如下
except
當(dāng)我們認(rèn)為一段代碼可能會出現(xiàn)錯誤時,我們可以使用 try 語句對錯誤進行處理,否則錯誤將一級級向上報,直到有函數(shù)可以處理該錯誤。若無函數(shù)處理該錯誤,程序?qū)⑼瞥鰣?zhí)行。
在出現(xiàn)錯誤時我們可以針對錯誤類型的不同,來輸出不同的結(jié)果
#!/usr/bin/evn python3
# -*- coding:utf-8 -*-
try:
r = 1 / 0
except ZeroDivisionError:
print ("The second number can't be zero!")
except ValueError:
print "Value Error."
執(zhí)行以上代碼,我們將得到以下結(jié)果
The second number can't be zero!
現(xiàn)在我們將代碼進行修改,修改后結(jié)果如下
#!/usr/bin/evn python3
# -*- coding:utf-8 -*-
try:
r = 1 / '1'
except ZeroDivisionError:
print ("The second number can't be zero!")
except ValueError:
print "Value Error."
執(zhí)行以上代碼,我們將得到以下結(jié)果
Value Error.
從以上代碼可以看出,針對不同的錯誤類型我們可以進行不同的輸出結(jié)果,在 Python 中常用的錯誤類型如下
| 異常 | 描述 |
|---|---|
| NameError | 嘗試訪問一個沒有申明的變量 |
| ZeroDivisionError | 除數(shù)為 0 |
| SyntaxError | 語法錯誤 |
| IndexError | 索引超出序列范圍 |
| KeyError | 請求一個不存在的字典關(guān)鍵字 |
| IOError | 輸入輸出錯誤(比如你要讀的文件不存在) |
| AttributeError | 嘗試訪問未知的對象屬性 |
在 try 語句中我們可以使用 else 和 finally 關(guān)鍵字,當(dāng)執(zhí)行 try 后的內(nèi)容 except 后的內(nèi)容被跳過時執(zhí)行 else 后的內(nèi)容;而 finally 后的語句無論前面執(zhí)行的是 try 后的語句還是 except 后的語句都會被執(zhí)行。
#!/usr/bin/evn python3
# -*- coding:utf-8 -*-
while True:
try:
x = raw_input("the first number:")
y = raw_input("the second number:")
r = float(x)/float(y)
except:
print('except try again')
else:
print('else')
finally:
print('finally')
執(zhí)行結(jié)果如下
the first number:1
the second number:2
else
finally
the first number:1
the second number:0
except try again
finally
try...except...在某些情況下能夠替代 if...else.. 的條件語句
大多數(shù)情況下 python 解釋器已經(jīng)給出了完善的錯誤提示信息,我們無需在單獨編寫提示信息,那我們我們該如何使用系統(tǒng)默認(rèn)的提示信息呢,我們可以通過參數(shù) e 來獲取系統(tǒng)默認(rèn)的提示信息。
#!/usr/bin/evn python3
# -*- coding:utf-8 -*-
while True:
try:
x = raw_input("the first number:")
y = raw_input("the second number:")
r = float(x)/float(y)
except ZeroDivisionError as e:
print(e)
else:
print('else')
finally:
print('finally')
執(zhí)行結(jié)果如下
the first number:1
the second number:0
float division by zero
finally
the first number:1
the second number:-
could not convert string to float: '-'
finally
the first number:1
the second number:1
else
finally
在以上代碼中我們并未編寫任何的錯誤提示信息,但是在出現(xiàn)錯誤時程序正常打印了錯誤信息 'float division by zero' 和 'could not convert string to float: '-''。