python try/except/finally
来源:互联网 发布:linux fuser 编辑:程序博客网 时间:2024/06/09 14:19
稍微总结一下,否则总是忘。
- 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
- 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/else/finally
- python try except finally raise
- python try except finally raise
- Python中的try...except...finally
- python try except else finally
- python 2.4 不支持 try-except-finally
- python中的try/except/else/finally语句
- Python中try...except...finally的理解
- python try..except..finally 实验【细节决定成败】
- Python中try,except,else,finally用法
- python中的try/except/else/finally语句
- C# 中的委托和事件
- 请别再拿“String s = new String("xyz");创建了多少个String实例”来面试了吧
- 数据库体系结构
- centos 6.4 恢复root用户上方面板的方法
- jQuery获取servlet返回的JSON
- python try/except/finally
- bitnami 版 gitlab 修改端口
- MFC下MD5加密算法实现,带key(32位MD5小写)
- WebService的创建,部署和使用
- c++中static的用法总结
- NSMutableAttributedString 的简单使用介绍
- w3c学习php笔记(一)
- 【python】错误 调试 测试try except finally raise
- android教学 listview再讲解