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

方式一:

try

检测范围

except Exception[ as reason]:

出现异常(Exception)后的处理代码

方式二:try-finally语句

try:

检测范围

except Exception[as reason]:

出现异常(Exception)后的处理代码

finally:

无论如何都会被执行的代码

raise语句

方式一:

try:

f= open('我为什么是一个文件.txt')print(f.read())

f.close()exceptOSError:print('文件出错拉T_T')

运行结果:

[fengjunjie@localhost ~]$ python3 test.py

文件出错拉T_T

try:

f= open('我为什么是一个文件.txt')print(f.read())

f.close()exceptOSError as reason:print('文件出错拉T_T,错误的原因是:' + str(reason))

运行结果:

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

文件出错拉T_T,错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件.txt'

try:

sum= 1 + '1'f= open('我为什么是一个文件.txt')print(f.read())

f.close()exceptOSError as reason:print('文件出错拉T_T,错误的原因是:' +str(reason))exceptTypeError:print('类型转换错误')

运行结果:

[fengjunjie@localhost ~]$ python3 test.py

类型转换错误

try:

int('abc')

sum= 1 + '1'f= open('我为什么是一个文件.txt')print(f.read())

f.close()exceptOSError as reason:print('文件出错拉T_T,错误的原因是:' +str(reason))exceptTypeError as reason:print('类型转换错误,错误原因' +str(reason))except:print('程序出错了')

运行结果:

[fengjunjie@localhost ~]$ python3 test.py

程序出错了

同时捕获多个异常:

try:

sum= 1 + '1'f= open('我为什么是一个文件.txt')print(f.read())

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

运行结果:

[fengjunjie@localhost ~]$ python3 test.py

程序出错了

方式二:

finally -- 文件关闭

try:

f= open('我为什么是一个文件.txt','w')print(f.write('我存在了!'))

sum= 1 + '1'

except(OSError,TypeError):print('程序出错了')finally:

f.close()

运行结果:

[fengjunjie@localhost ~]$ python3 test.py

5

程序出错了

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: 除书为零的异常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值