日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

python如何检测和处理异常_Python-20 异常处理 异常检测

發(fā)布時(shí)間:2025/3/20 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python如何检测和处理异常_Python-20 异常处理 异常检测 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

方式一:

try

檢測(cè)范圍

except Exception[ as reason]:

出現(xiàn)異常(Exception)后的處理代碼

方式二:try-finally語句

try:

檢測(cè)范圍

except Exception[as reason]:

出現(xiàn)異常(Exception)后的處理代碼

finally:

無論如何都會(huì)被執(zhí)行的代碼

raise語句

方式一:

try:

f= open('我為什么是一個(gè)文件.txt')print(f.read())

f.close()exceptOSError:print('文件出錯(cuò)拉T_T')

運(yùn)行結(jié)果:

[fengjunjie@localhost ~]$ python3 test.py

文件出錯(cuò)拉T_T

try:

f= open('我為什么是一個(gè)文件.txt')print(f.read())

f.close()exceptOSError as reason:print('文件出錯(cuò)拉T_T,錯(cuò)誤的原因是:' + str(reason))

運(yùn)行結(jié)果:

[fengjunjie@localhost ~]$ python3.6 test.py

文件出錯(cuò)拉T_T,錯(cuò)誤的原因是:[Errno 2] No such file or directory: '我為什么是一個(gè)文件.txt'

try:

sum= 1 + '1'f= open('我為什么是一個(gè)文件.txt')print(f.read())

f.close()exceptOSError as reason:print('文件出錯(cuò)拉T_T,錯(cuò)誤的原因是:' +str(reason))exceptTypeError:print('類型轉(zhuǎn)換錯(cuò)誤')

運(yùn)行結(jié)果:

[fengjunjie@localhost ~]$ python3 test.py

類型轉(zhuǎn)換錯(cuò)誤

try:

int('abc')

sum= 1 + '1'f= open('我為什么是一個(gè)文件.txt')print(f.read())

f.close()exceptOSError as reason:print('文件出錯(cuò)拉T_T,錯(cuò)誤的原因是:' +str(reason))exceptTypeError as reason:print('類型轉(zhuǎn)換錯(cuò)誤,錯(cuò)誤原因' +str(reason))except:print('程序出錯(cuò)了')

運(yùn)行結(jié)果:

[fengjunjie@localhost ~]$ python3 test.py

程序出錯(cuò)了

同時(shí)捕獲多個(gè)異常:

try:

sum= 1 + '1'f= open('我為什么是一個(gè)文件.txt')print(f.read())

f.close()except(OSError,TypeError):print('程序出錯(cuò)了')

運(yùn)行結(jié)果:

[fengjunjie@localhost ~]$ python3 test.py

程序出錯(cuò)了

方式二:

finally -- 文件關(guān)閉

try:

f= open('我為什么是一個(gè)文件.txt','w')print(f.write('我存在了!'))

sum= 1 + '1'

except(OSError,TypeError):print('程序出錯(cuò)了')finally:

f.close()

運(yùn)行結(jié)果:

[fengjunjie@localhost ~]$ python3 test.py

5

程序出錯(cuò)了

raise

>>> raise

Traceback (most recent call last):

File "", line 1, in

RuntimeError: No active exception to reraise

>>> raise ZeroDivisionError

Traceback (most recent call last):

File "", line 1, in

ZeroDivisionError

>>> raise ZeroDivisionError('除書為零的異常')

Traceback (most recent call last):

File "", line 1, in

ZeroDivisionError: 除書為零的異常

總結(jié)

以上是生活随笔為你收集整理的python如何检测和处理异常_Python-20 异常处理 异常检测的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。