【脚本语言系列】关于Python基础知识异常处理,你需要知道的事

如何使用异常处理

  • try,except单个异常
# -*- coding:utf-8 -*-
try:
    file = open('log.log', 'rb')
except IOError as e:
    print "IOError occured. {}".format(e.args[-1])
IOError occured. No such file or directory
The note always shows up.
  • try,except多异常
# -*- coding:utf-8 -*-
try:
    file = open('log.log', 'rb')
except (IOError, EOFError) as e:
    print "IOError occured. {}".format(e.args[-1])
finally:
    print "The note always shows up."
IOError occured. No such file or directory
The note always shows up.
# -*- coding:utf-8 -*-
try:
    file = open('log.log', 'rb')
except IOError as e:
    print "IOError occured. {}".format(e.args[-1])
    raise e
except EOFError as e:
    print "EOFError occured. {}".format(e.args[-1])    
    raise e
finally:
    print "The note always shows up."
IOError occured. No such file or directory
The note always shows up.



---------------------------------------------------------------------------

IOError                                   Traceback (most recent call last)

<ipython-input-6-d7ccfce08e95> in <module>()
      4 except IOError as e:
      5     print "IOError occured. {}".format(e.args[-1])
----> 6     raise e
      7 except EOFError as e:
      8     print "EOFError occured. {}".format(e.args[-1])


IOError: [Errno 2] No such file or directory: 'log.log'
# -*- coding:utf-8 -*-
try:
    file = open('log.log', 'rb')
except Exception:
    print "Error occured."    
finally:
    print "The note always shows up."
    raise
Error occured.
The note always shows up.



---------------------------------------------------------------------------

IOError                                   Traceback (most recent call last)

<ipython-input-8-8f493882cb97> in <module>()
      1 
      2 try:
----> 3     file = open('log.log', 'rb')
      4 except Exception:
      5     print "Error occured."


IOError: [Errno 2] No such file or directory: 'log.log'
  • finally收尾
# -*- coding:utf-8 -*-
try: 
    file = open('log.log', 'rb')
except IOError as e:
    print "IOError occurred. {}".format(e.args[-1])
finally:
    print "The note always shows up."
IOError occurred. No such file or directory
The note always shows up.
  • try,else正常
# -*- coding:utf-8 -*-
try:
    print "There is no exception."
except Exception:
    print "Exception."
else:
    print "No Exception at all."
finally:
    print "The note always shows up."
There is no exception.
No Exception at all.
The note always shows up.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值