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

python - try/except/else/finally

2014-04-16 12:47 288 查看
什么是异常 ?

异常是程序在执行过程中产生的事件,它会破坏正常的程序执行流程。通常,当Python脚本遇到它无法处理的情况时,就会产生异常。

一个异常是一个Python对象,它代表一个错误。Python脚本出现异常时,你需要处理它,不然脚本程序就会被终止并退出。

try:

    .... #  程序主体代码块

except exception1:  # 捕获到异常exception1,执行此处代码块expA

    ....  # 代码块 expA

except exception 2: # 捕获到异常exception2,执行此处代码块expB

    ....  # 代码块 expB

except: # 其它未捕获的异常,交给此处处理.

    ....  # 代码快 expCDEFG...

else: # 程序无异常,执行此处代码

    ....

finally: # 不管是否异常,均执行的代码

    ....

#!/usr/bin/python

try:
# -------- 程序代码主体[起始] -----------
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
# -------- 程序代码主体[结束] -----------

except IOError: # 出现某种异常,执行该部分代码
print "Error: can\'t find file or read data"

else: # 无异常出现,执行下面代码
print "Written content in the file successfully" fh.close()

try:
You do your operations here;
......................
# except 后面,若不跟异常类型,则表示捕获所有异常,
# 不推荐这么做,这会降低程序效率,也容易养成不好的编程习惯
except(Exception1[, Exception2[,...ExceptionN]]]): # 出现其中的任何一种异常,执行下面代码
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.

try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally: # 不管是否异常,都执行下面代码
This would always be executed.
......................


参考链接:
http://www.tutorialspoint.com/python/python_exceptions.htm http://stackoverflow.com/questions/855759/python-try-else https://docs.python.org/2/tutorial/errors.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: