您的位置:首页 > 编程语言 > Python开发

【脚本语言系列】关于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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐