python异常简单使用方法

来源:互联网 发布:淘宝订单待清洗 编辑:程序博客网 时间:2024/04/29 22:39
1. try...except 
Python代码  收藏代码
  1. tommy@lab3:~$ python  
  2. Python 2.5.2 (r252:60911, Jan  4 200917:40:26)  
  3. [GCC 4.3.2] on linux2  
  4. Type "help""copyright""credits" or "license" for more information.  
  5. >>> 1/0  
  6. Traceback (most recent call last):  
  7.   File "<stdin>", line 1in <module>  
  8. ZeroDivisionError: integer division or modulo by zero  
  9. >>>  
  10. >>> try:  
  11. ...     1/0  
  12. ... except:  
  13. ...     print "do something..."  
  14. ...  
  15. do something...  
  16. >>>  


2. try...finally 

finally 里面只是执行完成try中的代码后,必须执行的代码, 
即使是 try中有异常抛出,也是会去执行finally 

Python代码  收藏代码
  1. >>> try:  
  2. ...     1/0  
  3. ... finally:  
  4. ...     print "I just finally do something ,eg: clear!"  
  5. ...  
  6. I just finally do something ,eg: clear!  
  7. Traceback (most recent call last):  
  8.   File "<stdin>", line 2in <module>  
  9. ZeroDivisionError: integer division or modulo by zero  
  10. >>>  


所以,一般情况下,finally里面执行的都是一些清理工作,比如:关闭文件描述符,释放锁等 

Python代码  收藏代码
  1. >>> try:  
  2. ...     fd=open("have-exists-file""r")  
  3. ...     print "do some thing ,read file ,write file..."  
  4. ... finally:  
  5. ...     fd.close()  
  6. ...  
  7. do some thing ,read file ,write file...  
  8. >>>  


多线程中,对锁的使用 

Python代码  收藏代码
  1. tommy@lab3:~$ python  
  2. Python 2.5.2 (r252:60911, Jan  4 200917:40:26)  
  3. [GCC 4.3.2] on linux2  
  4. Type "help""copyright""credits" or "license" for more information.  
  5. >>> import threading  
  6. >>> l_lock=threading.RLock()  
  7. >>> try:  
  8. ...     l_lock.acquire()  
  9. ...     print "do some thing."  
  10. ... finally:  
  11. ...     l_lock.release()  
  12. ...  
  13. True  
  14. do some thing.  
  15. >>>  



注意,finally中,如果出现异常,外部如果没有相应的捕获机制,该异常会层层抛出,直到最顶端,然后解释器停止 
一般我们会这样做 
Python代码  收藏代码
  1. >>> try:  
  2. ...     try:  
  3. ...         fd=open("no-exists-file""r")  
  4. ...         print "do some thing ,read file ,write file..."  
  5. ...     finally:  
  6. ...         fd.close()  
  7. ...except:  
  8. ...    print "catch finally exception."  
  9. do some thing ,read file ,write file...  
  10. >>>  


3. 封装了一个全局的捕获异常的函数(偶比较懒,就用了全部的捕获异常方法) 

Python代码  收藏代码
  1. import traceback  
  2. import sys  
  3. def trace_back():  
  4.     try:  
  5.         return traceback.print_exc()  
  6.     except:  
  7.         return ''  


http://www.iteye.com/topic/416890


Python代码  收藏代码
  1. try:  
  2.     do_something()  
  3. except:  
  4.     print trace_back()