Python知識點8 錯誤與異常處理

2021-10-24 11:20:29 字數 2504 閱讀 5282

python知識點8:錯誤與異常處理

b站學習:

一、異常簡介

1.捕獲異常

ioerror異常

#捕獲異常

try:

print

("前"

) f=

open

("123.txt"

,"r"

)#檔案不存在,會出現filenotfounderror

print

("後"

)#pass:不會被執行

except ioerror:

#檔案沒找到屬於ioerror

pass

nameerror異常

try

:print

(num)

#num沒有宣告

except nameerror:

print

("產生錯誤了"

)

捕獲多種異常並獲取錯誤資訊

try

:print

("前"

) f=

open

("123.txt"

,"r"

)#檔案不存在,會出現filenotfounderror

print

("後"

)#中斷了,不會被執行

print

(num)

#中斷了,不會被執行

except

(ioerror,nameerror)

as result:

#將所有有可能發生的異常寫出來

print

("產生錯誤了"

)print

(result)

#獲取錯誤資訊

捕獲所有異常

try

:print

("前"

) f=

open

("123.txt"

,"r"

)#檔案不存在,會出現filenotfounderror

print

("後"

)#中斷了,不會被執行

print

(num)

#中斷了,不會被執行

except exception as result:

#exception表示所有可能出現的異常

print

("產生錯誤了"

)print

(result)

#獲取錯誤資訊

巢狀以及finally

#巢狀

import time

try:

f=open

("test.txt"

,"r"

)try

:while

true

: content=f.readline()if

len(content)==0

:break

time.sleep(2)

print

(content)

finally

:#一定會被執行

f.close(

)print

("檔案關閉"

)except exception as result:

print

("發生異常"

)

二、課後練習

#課後練習

defwritefile

(f):

poem=

input

("請輸入古詩詞"

) f.write(poem)

defcopyfile

(a,b)

: content=a.readlines(

)for i in content:

b.write(i)

f=open

("gushi.txt"

,"w"

,encoding=

"utf-8"

)writefile(f)

f.close()f=

open

("gushi.txt"

,"r"

,encoding=

"utf-8")g=

open

("copy.txt"

,"w"

,encoding=

"utf-8"

)copyfile(f,g)

f.close(

)g.close(

)

結果

python 異常知識點

python 在3.0 之後引入了raise from 表示式 raise exception from otherexception 當使用該語法時,第二個表示式指定了另乙個異常類或例項,它會附加到引發異常的 cause 屬性 注意 python3.0不再支援raise exc,args形式,而該...

知識點小結 異常

1.異常 try catch 錯誤 error 無法解決 1.try catch 程式的流程是 執行到try塊中,如果有異常丟擲,則轉到catch塊去處理。然後執行catch塊後面的語句 2.try catch finally 程式的流程是 執行到try塊中,如果有異常丟擲,則轉到catch塊,ca...

python語言篇(8知識點)

函式變數 函式名是變數,它在建立時繫結乙個函式 示例 def f1 lst print f1函式被呼叫 f1 f1 none f1 出錯,f1 繫結的是none 示例 def f1 print hello def f2 print world f1,f2 f2,f1 f1 world 乙個函式可以作...