python之異常處理

2022-08-14 15:42:15 字數 1960 閱讀 1560

下面的例子可以方便的理解異常處理的流程:

sep = '

-' * 32 + '\n'

print(sep + '

exception raised and caught')

try:

x = '

spam

'[9]

except

indexerror:

print('

except run')

finally

:

print('

finally run')

print('

after run')

print(sep + '

no exception raised')

try:

x = '

spam

'[3]

except

indexerror:

print('

except run')

finally

:

print('

finally run')

print('

after run')

print(sep + '

no exception raised, with else')

try:

x = '

spam

'[3]

except

indexerror:

print('

except run')

else

:

print('

else run')

finally

:

print('

finally run')

print('

after run')

print(sep + '

exception raised but not caught')

try:

x = 1 /0

except

indexerror:

print('

except run')

finally

:

print('

finally run')

print('

after run

')

view code

輸出:

traceback (most recent call last):

--------------------------------file

"f:/xhbproject/fenci_test/cdn-api/test.py

", line 36, in

exception raised and caught

except

runfinally

run x = 1 /0

after run

zerodivisionerror: division by zero

--------------------------------no exception raised

finally

runafter run

--------------------------------no exception raised, with else

else

runfinally

runafter run

--------------------------------exception raised but not caught

finally run

可以看出:

else子句是在沒有發生異常的情況下執行的,finally子句是不管有沒有異常都會執行,try語句塊後的語句是在沒有異常或異常被程式捕獲處理後才會執行。

python之異常處理 Python之異常處理

異常物件 請大家執行如下 a 100 0 print a 就會發現直譯器顯示如下的錯誤提示 traceback most recent call last file x.py line 1,in a 100 0 zerodivisionerror division by zero 大家要學會看直譯器...

Python之異常處理

在程式執行過程中影響程式正常執行的內容,稱為異常 nameerror print a indexerror 索引錯誤 li 1,2,3,4 print li 8 keyerror d dict a 1,b 2 print d f zerodivisionerror 除0錯誤 print 10 2 2...

Python之異常處理

try ret int input num 正常執行的 print ret except valueerror 捕捉錯誤 print 請輸入數字 try ret int input num 正常執行的 print ret except valueerror 捕捉錯誤 print 請輸入數字 exce...