2011年3月10日

example code for python exception

>>>>>> try:  
raise Exception("a", "b")
except Exception,e:
print e
finally:
print "final"


(
'a', 'b')('a', 'b')
final
>>>>>>  
deal with muti exception 
 >>>>>> try:  
raise EOFError("aa", "bb")
except RuntimeError, e:
print "[RuntimeErro]: ", e
except EOFError, e:
print "[EOFError]: ", e
except Exception, e:
print "[Error]: ", e
finally
 
[EOFError]:  ('aa', 'bb')  
final
>>>>>>

 

get error information using sys。

 

Code
>>>>>> import sys
>>>>>> try:
raise RuntimeError("the runtime error raised")
except:
print sys.exc_info()


(
<type 'exceptions.RuntimeError'>, RuntimeError('the runtime error raised',), <traceback object at 0x00DC5CB0>)
>>>>>>
print "final"

--
we drink green tea

python try-except example

try...except 
Python code  收藏代码
  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 

after code in try ,code in finally will run 

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. >>>  


 

Python code  收藏代码
  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. >>>  

--
we drink green tea