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: # 不管是否异常,均执行的代码
....
参考链接:
http://www.tutorialspoint.com/python/python_exceptions.htm http://stackoverflow.com/questions/855759/python-try-else https://docs.python.org/2/tutorial/errors.html
异常是程序在执行过程中产生的事件,它会破坏正常的程序执行流程。通常,当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
相关文章推荐
- python try except else finally
- python try...except....else...finally处理异常
- Python学习笔记之错误处理(关键词:错误处理、异常机制、try、except、else、finally、raise)
- Python-try except else finally有return时执行顺序探究
- python 异常错误 try except else finally
- python中的try/except/else/finally语句
- Python中try,except,else,finally用法
- python 异常处理-try-except-else-finally
- python中的异常处理:try...except...else...finally语句
- python try except else finally 执行顺序详细分析
- python中的try/except/else/finally语句
- python try except else finally 执行顺序详细分析
- python中的try/except/else/finally语句
- python中的try/except/else/finally语句--自我小结
- Python异常捕捉try except else finally有return时执行顺序探究
- python try except else finally 执行顺序详细分析
- Python中的异常处理: try-except-else-finally
- 11、python中的try/except/else/finally语句
- python try except else finally 执行顺序详细分析
- python异常处理try,except,else,finally,raise