python异常捕获_python异常捕获try except

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 "", line 1, in

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 "", line 2, in

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

具体使用

try:

do_something()

except:

print trace_back()

写的比较散,主要是想说说,python异常的简单使用,已经封装的一个简单的获得异常发生时,全局保持的异常信息(可能不准确,但基本够用)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值