Python进阶——异常处理

异常处理

try/except从句。
将可能触发异常产生的代码放到try模块里,而处理异常的代码会在except语句块里实现。如:

try:
    file=open('test.txt','rb')
except IOError as e:
    print('An IOError occured. {}'.format(e.args[-1]))
输出:
  An IOError occured. No such file or directory

处理多个异常

try:
    file=open('test.txt','rb')
except (IOError,EOFError) as e:
    print('An IOError occured. {}'.format(e.args[-1]))

或者:

try:
    file=open('test.txt','rb')
except EOFError as e:
    print('An IOError occured. {}'.format(e.args[-1]))
    raise e
except IOError as e:
    print('An IOError occured. {}'.format(e.args[-1]))
    raise e

捕获所有异常

try:
    file=open('test.txt','rb')
except Exception:
    #打印一些异常日日志
    raise

finally从句

在上面异常处理语句中,有try从句和except从句,我们还会使用第三个从句就是finally从句。在finally从句中的代码不管异常是否触发都将会被执行。可以被用来在脚本结束执行后做清理工作。
比如:

try:
    file=open('test.txt','rb')
except IOError as e:
    print('An IOError occured. {}'.format(e.args[-1]))
finally:
    print("this would be printed whether or not an error")
    输出:
    An IOError occured. No such file or directory
this would be printed whether or not an error

try/else从句

如果在异常处理语句中,想让一些代码在没有触发异常的情况下执行,就要使用else从句了,为啥不直接把执行代码放try里呢,是因为如果放在try里这段代码的任何异常也会被try捕获。
比如:

try:
    print('I am sure no error')
except:
    print('exception')
else:
    print("This would be printed if no error")
finally:
    print("This would be printed every case")
输出:
I am sure no error
This would be printed if no error
This would be printed every case
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值