一文读懂Python中的异常处理

异常处理在任何一门编程语言里都是值得关注的一个话题,良好的异常处理可以让你的程序更加健壮,清晰的错误信息更能帮助你快速修复问题。在Python中,和不部分高级语言一样,使用了try/except/finally语句块来处理异常,如果你有其他编程语言的经验,实践起来并不难。

异常处理语句 try...excpet...finally

实例代码

defdiv(a, b):

try:

print(a / b)

exceptZeroDivisionError:

print("Error: b should not be 0 !!")

exceptExceptionase:

print("Unexpected Error: {}".format(e))

else:

print('Run into else only when everything goes well')

finally:

print('Always run into finally block.')

# tests

div(2,0)

div(2,'bad type')

div(1,2)

# Mutiple exception in one line

try:

print(a / b)

except(ZeroDivisionError, TypeError)ase:

print(e)

# Except block is optional when there is finally

try:

open(database)

finally:

close(database)

# catch all errors and log it

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值