- tommy@lab3:~$ python
- Python 2.5.2 (r252:60911, Jan 4 2009, 17:40:26)
- [GCC 4.3.2] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> 1/0
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ZeroDivisionError: integer division or modulo by zero
- >>>
- >>> try:
- ... 1/0
- ... except:
- ... print "do something..."
- ...
- do something...
- >>>
2. try...finally
finally 裏面只是執行完成try中的代碼後,必須執行的代碼,
即使是 try中有異常拋出,也是會去執行finally
- >>> try:
- ... 1/0
- ... finally:
- ... print "I just finally do something ,eg: clear!"
- ...
- I just finally do something ,eg: clear!
- Traceback (most recent call last):
- File "<stdin>", line 2, in <module>
- ZeroDivisionError: integer division or modulo by zero
- >>>
所以,一般情況下,finally裏面執行的都是一些清理工作,比如:關閉文件描述符,釋放鎖等
- >>> try:
- ... fd=open("have-exists-file", "r")
- ... print "do some thing ,read file ,write file..."
- ... finally:
- ... fd.close()
- ...
- do some thing ,read file ,write file...
- >>>
多線程中,對鎖的使用
- tommy@lab3:~$ python
- Python 2.5.2 (r252:60911, Jan 4 2009, 17:40:26)
- [GCC 4.3.2] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> import threading
- >>> l_lock=threading.RLock()
- >>> try:
- ... l_lock.acquire()
- ... print "do some thing."
- ... finally:
- ... l_lock.release()
- ...
- True
- do some thing.
- >>>
注意,finally中,如果出現異常,外部如果沒有相應的捕獲機制,該異常會層層拋出,直到最頂端,然後解釋器停止
一般我們會這樣做
- >>> try:
- ... try:
- ... fd=open("no-exists-file", "r")
- ... print "do some thing ,read file ,write file..."
- ... finally:
- ... fd.close()
- ...except:
- ... print "catch finally exception."
- do some thing ,read file ,write file...
- >>>
3. 封裝了一個全局的捕獲異常的函數(偶比較懶,就用了全部的捕獲異常方法)
- import traceback
- import sys
- def trace_back():
- try:
- return traceback.print_exc()
- except:
- return ''
http://www.iteye.com/topic/416890
- try:
- do_something()
- except:
- print trace_back()