Python 快速入門筆記(8) 異常處理

2022-08-19 07:36:10 字數 2941 閱讀 5161

python 中的異常處理有許多與 c++ 中類似的部分,比如 raise 語句與 c++ 中的 throw 語句相似, try-except 語句與 c++ 中的 try-catch 語句相似。

當然也有一些不同的地方,比如:python 中可以捕獲「除數為0」這種執行時錯誤,而 c++ 就不能,例如:

x = int(input("

enter the first number: "))

y = int(input("

enter the second number: "))

try:

print("

result is %f

" % (x /y))

except zerodivisionerror: #

當 y 的值為 0 時,這裡就能捕獲到異常

print("

the second number is zero

")

除了「除數為0」這種程式自發的錯誤,我們還可以在某些不合法的情形下,使用 raise 語句人為地丟擲異常。

raise 語句可以帶乙個引數,這個引數必須是乙個(繼承自 exception 類的)類或者乙個例項物件,如果引數是類的話,會自動建立乙個該類的例項物件。

raise 語句也可以不帶引數(通常用於 except 語句中,表明已經捕獲到了某個異常物件),向上繼續傳遞當前捕獲到的異常物件(如果外圍沒有捕獲該異常,則程式中斷並報錯)。

示例:

def

foo(n):

if n < 1:

raise exception #

人為丟擲異常

while n >0:

x = int(input("

enter the first number: "))

y = int(input("

enter the second number: "))

try:

print("

result is %f

" % (x /y))

except zerodivisionerror: #

捕獲 除數為0 的異常

print("

the second number is zero")

raise

#繼續傳遞 zerodivisionerror 異常

n -= 1

try:

foo(5)

except: #

捕獲任意異常

print("

an exception was caught, stop running

")

下圖列舉了一些常用的內建異常類:

注:上圖截自《python基礎教程》第8章。

關於異常捕獲:

示例:

def

test(e):

try:

if (not

e):

pass

else

:

raise

e

except zerodivisionerror: #

捕獲單個型別異常

print("

caught a zerodivisionerror exception")

except (typeerror, valueerror): #

捕獲多個型別異常

print("

caught either a typeerror exception or a valueerror exception")

except (indexerror, keyerror) as e: #

捕獲異常物件

print("

caught an exception object

", e)

except: #

捕獲任意異常

print("

caught an unknown exception")

raise

else: #

沒有異常發生時才會執行

print("

no exception")

finally: #

總是會執行到這裡

print("

finally")

#下面每一次 test() 呼叫後都會輸出 finally,省略了未列出

test(zerodivisionerror) #

caught a zerodivisionerror exception

test(typeerror) #

caught either a typeerror exception or a valueerror exception

test(valueerror) #

caught either a typeerror exception or a valueerror exception

test(indexerror) #

('caught an exception object', indexerror())

test(keyerror) #

('caught an exception object', keyerror())

test(exception) #

caught an unknown exception

test(none) #

no exception

完。

python快速學習系列(8) 異常處理

異常通常出現的處理方式 條件語句 if else 異常處理 try except else finally 1.python中的異常和相關語法 exception python內建的異常類 raise 丟擲異常 try 嘗試執行以下語句 except 在try語句之後,捕獲某個異常,為空則捕獲全部異...

第8章 Python筆記 異常

一 按照自己的方式出錯 1 raise語句 raise語句可以引發異常 raise exception traceback most recent call last file line 1,in raise exception exception raise exception hyperdriv...

Python學習筆記 快速入門

使用換行來表示乙個語句的結束。但如果一行內出現了多個語句,請使用分號 進行語句分隔。print hello,world print hello print world 使用縮排來表示一段 段,作者喜歡用tab鍵 已設定為4個空格 來進行縮排。if true print hello print wor...