程式在執行過程中不可避免會出現一些錯誤
例如:nameerror、valueerror、typeerror…
這些錯誤在程式中就叫做異常
這是因為,在程式執行過程中,一旦出現異常,程式就會被中斷。異常後面的**都不會再執行。print('hello')
print(a)
print('python')
結果只列印了hello,python並沒有被列印
程式出現異常,目的並不是程式立即終止,python是希望在出現異常時,我們可以編寫**對異常進行處理。
處理方法:
語法:
舉例:異常處理try:
**塊(可能出現錯誤的語句)
except 異常型別 as 異常物件:
**塊(出現錯誤後的處理邏輯)
except 異常型別 as 異常物件:
**塊(出現錯誤後的處理邏輯)
except 異常型別 as 異常物件:
**塊(出現錯誤後的處理邏輯)
....
else:
**塊(沒有錯誤時要執行的語句)
finally:
**塊(有無異常都會執行該**)
若try後面的**塊沒有出錯則執行else後面的語句而不執行except後的語句print('hello')
try:
#有可能出現錯誤的**
print(20/0)
except:
#錯誤出現後執行的**
print('出錯啦...')
else:
#沒有出錯執行的**
print('程式正常執行')
print('python')
輸出結果:
hello
出錯啦...
python
若try後面的**塊出錯了,則執行except後面的語句而不執行else後的語句
當在函式**現異常時,如果在函式中進行了處理,則異常不會再傳播
如果沒有在函式中進行處理,則異常會向函式呼叫處傳播
在函式呼叫處處理異常def fn():
print('hello...')
print(a)
fn()
會報兩個錯誤,在函式中和函式呼叫處都會報錯(print(a)報錯、fn()報錯)
如果函式呼叫處處理了異常,則不再傳播;如果沒有處理,則繼續向函式呼叫處傳播,直到傳遞到全域性作用域,如果依然沒有處理,則程式終止,並顯示異常資訊def fn():
print('hello...')
print(a)
try:
fn()
except:
pass
從fn1傳遞到fn2傳遞到fn3然後傳遞到fn3()def fn1():
print('hello fn1')
print(20/0)
def fn2():
print('hello fn2')
fn1()
def fn3():
print('hello fn3')
fn2()
fn3()
當程式執行過程**現異常,所有的異常資訊會儲存到乙個異常物件中
當異常傳播時,實際上就是異常物件拋給了函式呼叫處
每個異常都會有專門的乙個類來進行處理。zerodivisionerror就是專門用來處理除0錯誤的。
except可以捕獲所有的出錯物件,但無法判斷出錯的型別
zerodivisionerror和nameerror都會**獲,但不知道具體是什麼型別,我們可以在except後面加上異常型別,專門用來處理某一類異常print('異常出現前')
try:
print(20/0)
print(z)
except:
print('出錯啦...')
print('出現異常後')
異常類有很多,不可能在**中處理所有型別的異常,我們可以在except後新增exception(exception是所有異常的父類),它會捕獲到所有的異常,我們可以通過檢視異常物件(只能檢視第乙個異常),來確認異常資訊print('異常出現前')
try:
print(20/0)
print(z)
except nameerror:
#專門處理nameerror錯誤,仍會報zerodivisionerror錯誤
print('出現nameerror錯誤')
print('出現異常後')
finally無論是否出現異常都會執行其後的**print('異常出現前')
try:
print(20/0)
print(z)
except exception as e:
#e為異常物件,其內容為異常資訊,可以通過type(e)來檢視異常型別
print('出現異常',e,type(e))
#輸出結果:出現異常 division by zero print('出現異常後')
可以利用raise語句丟擲異常print('異常出現前')
try:
print(20/0)
print(z)
except exception as e:
print('出現異常',e,type(e))
finally:
#無論是否有異常都會執行該**塊
print('hello.....')
print('出現異常後')
raise後需要新增乙個異常類或異常的例項
丟擲異常的目的是為了告訴呼叫者在呼叫函式時可能有問題,需要呼叫者自己處理
定義乙個異常類,只需要繼承異常類(exception)就可以def add(a,b):
#如果a,b中有乙個是負數,則丟擲異常
if a<0 or b<0:
raise exception('引數中不能有負數')
r= a+b
return r
print(add(-1,2))
輸出結果:
exception: 引數中不能有負數
#自定義異常類
class myerror(exception):
pass
def add(a,b):
#如果a,b中有乙個是負數,則丟擲異常
if a<0 or b<0:
raise myerror('自定義異常資訊')
r= a+b
return r
print(add(-1,2))
輸出結果:
__main__.myerror: 自定義異常資訊
Python 15 異常處理
def get score while true try int score int input 請輸入成績 except exception as s print 有異常,重新輸入 s continue if 0 int score 100 print int score break get sc...
python基礎 異常處理
1 0 name 2 3 3 k try print 1111 1 0 print 2222 name 2 3 3 k ret int input number print ret except valueerror print 輸入的資料型別有誤 except exception print 你錯...
python基礎 異常處理
異常是程式執行過程 現的非正常流程現象。異常是無法避免的,只能先預估出可能出現的異常現象,並提供對應的處理機制,在異常出現後保障程式不被中斷執行。格式一 常用 try 可能引發異常現象的 except 出現異常現象的處理 格式二 不常用 try 可能引發異常現象的 finally try 塊結束後執...