要引起異常,能夠使用raise語句,並將一個類或實例做爲參數,將類做爲參數時,將自動建立一個實例函數
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exceptionspa
常見的異常類型:操作系統
Exception 幾乎全部異常類都從它派生對象
AttributeError 引用屬性或給它賦值失敗時引起繼承
OSError 操做系統不能執行指定的任務時引起索引
IndexError 使用序列中不存在的索引時引起,爲LookupError的子類input
KeyError 使用映射中不存在的鍵時引起,爲LoolupError的子類io
NameError 找不到名稱或變量時引起ast
SytaxError 代碼不正確時引起class
TypeError 將內置操做或函數用於類型不正確發的對象時引起
ValueErroe 將內置操做或函數用於這樣的對象時引起:其類型正確但包含的值不合適
ZeroDivisionError 在除法或求模運算的第二個參數爲零時引起
自定義異常類:務必直接或間接繼承Expection,意味從任何內置異常類派生均可以
class SonmeCustomExpection(Expection):
pass
捕獲異常:try/except
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x/y)
except ZeroDivisionError:
print("The second number can't be zero")
捕獲多種異常:
except( ZeroDivisionError, TypeError):
捕獲全部異常(不指定任何異常):
except: