python try except finally raise
来源:互联网 发布:如何使用淘宝口令 编辑:程序博客网 时间:2024/05/30 05:25
python try except finally raise
2014-08-02 10:43 17人阅读 评论(0) 收藏 举报
稍微总结一下,否则总是忘。
- x = 'abc'
- def fetcher(obj, index):
- return obj[index]
- fetcher(x, 4)
输出:
- File "test.py", line 6, in <module>
- fetcher(x, 4)
- File "test.py", line 4, in fetcher
- return obj[index]
- IndexError: string index out of range
第一: try不仅捕获异常,而且会恢复执行
- def catcher():
- try:
- fetcher(x, 4)
- except:
- print "got exception"
- print "continuing"
- got exception
- continuing
第二:无论try是否发生异常,finally总会执行
- def catcher():
- try:
- fetcher(x, 4)
- finally:
- print 'after fecth'
- after fecth
- Traceback (most recent call last):
- File "test.py", line 55, in <module>
- catcher()
- File "test.py", line 12, in catcher
- fetcher(x, 4)
- File "test.py", line 4, in fetcher
- return obj[index]
- IndexError: string index out of range
第三:try无异常,才会执行else
- def catcher():
- try:
- fetcher(x, 4)
- except:
- print "got exception"
- else:
- print "not exception"
- got exception
- def catcher():
- try:
- fetcher(x, 2)
- except:
- print "got exception"
- else:
- print "not exception"
- not exception
第四:利用raise传递异常
- def catcher():
- try:
- fetcher(x, 4)
- except:
- print "got exception"
- raise
- got exception
- Traceback (most recent call last):
- File "test.py", line 37, in <module>
- catcher()
- File "test.py", line 22, in catcher
- fetcher(x, 4)
- File "test.py", line 4, in fetcher
- return obj[index]
- IndexError: string index out of range
异常在程序代码中消失,可以通过raise重新引发该异常。
第五:except(name1, name2)
- def catcher():
- try:
- fetcher(x, 4)
- except(TypeError, IndexError):
- print "got exception"
- else:
- print "not exception"
- def catcher():
- try:
- fetcher(x, 4)
- except:
- print "got exception"
0 0
- python try except finally raise
- python try except finally raise
- 【python】错误 调试 测试try except finally raise
- 【python】错误 调试 测试try except finally raise
- Python异常处理try...except...finally raise assert
- python中的异常处理try/except/finally/raise
- python try/except/finally
- python try/except/finally
- python try/except/finally
- python try/except/finally
- python try/except/finally
- python try/except/finally
- python try/except/finally
- Python--小甲鱼学习笔记--第33课:异常处理(try-except, try-finally, raise)
- python异常图解:try、raise、except、else、finally块用法简要说明
- (Python)异常处理try...except、raise
- (Python)异常处理try...except、raise
- Python异常处理try...except、raise
- 互联网时代:致敬技术先驱
- HDU 2147 kiki's game 简单博弈
- 汉子如何按照16进制打印出来
- (八)动画与动作
- 多线程网络
- python try except finally raise
- 祭奠我逝去的青春,憧憬我大学的时光。
- 【leetcode】swap-nodes-in-pairs
- UML之用例图
- Android开发之简单的聊天室(客户端与服务器进行通信)
- 共享池---Heap、Extent、Chunk、Free List
- qml部署ios播放声音的一些问题
- 用 JavaScript + jQuery,制作简单的 “订餐"页面
- Android利用canvas画各种图形(点、直线、弧、圆、椭圆、文字、矩形、多边形、曲线、圆角矩形)