Python——异常处理

异常

最基本的术语是try/except从句,将可能触发异常产生的代码放到try语句块里,而异常处理的代码会在except语句块里实现。

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

处理多个异常

第一种方法需要把所有可能发生的异常放到一个元组里。

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

第二种方法是对每个单独的异常在单独的except语句块中处理。

try:
    file = open('test,txt', 'rb')
except IOError as e:
    print("An IOError occurred")
    raise e
except EOFError as e:
    print("An EOF error occurred")
    raise e

如果第一个异常没有被第一个except语句块处理,那么就会被下一个语句块处理或者根本不会被处理。

最后一种捕获所有异常

try:
    file = open('test,txt', 'rb')
except Exception:
    raise

当你们不知道程序抛出什么异常,就可以使用这个。

finally从句

finally从句中的代码不管异常是否触发都将会触发执行,这可以被用在脚本执行之后做清理工作。

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

finally:
    print("This would be printed whether or not an exception occurred!")

"""
An IOError occurred. No such file or directory
This would be printed whether or not an exception occurred!
"""

try/else从句

常常想在没有触发异常的时候执行一些代码。这可以很轻松地通过一个else从句来达到。

try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # 这里的代码只会在try语句里没有触发异常时运行,
    # 但是这里的异常将 *不会* 被捕获
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')
# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs.
# This would be printed in every case.

else从句只会在没有异常的情况下执行,而且它会在finally语句之前执行。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值