【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
2017-07-19 14:00
871 查看
如何使用异常处理
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.
相关文章推荐
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python基础知识迭代器,你需要知道的事
- 【脚本语言系列】关于Python基础知识兼容Python 2.x+Python 3.x,你需要知道的事
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- 【脚本语言系列】关于Python基础知识Lambda表达式,你需要知道的事
- 【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 【脚本语言系列】关于Python基础知识文件操作,你需要知道的事
- 【脚本语言系列】关于Python基础知识函数缓存,你需要知道的事
- 【脚本语言系列】关于Python基础知识设计模式,你需要知道的事
- 【脚本语言系列】关于Python基础知识装饰器,你需要知道的事
- 【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事
- 【脚本语言系列】关于Python基础知识多返回值,你需要知道的事
- 【脚本语言系列】关于Python基础知识协程,你需要知道的事
- 【脚本语言系列】关于Python基础知识枚举,你需要知道的事
- 【脚本语言系列】关于Python基础知识容器,你需要知道的事
- 【脚本语言系列】关于Python异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识推导式,你需要知道的事