使用try / finally处理异常的最佳方法 [英] Best way to handle exceptions with try/finally

查看:151
本文介绍了使用try / finally处理异常的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿python人,


我有兴趣使用try / finally子句确保优雅

清理,无论代码块如何退出。但是,我仍然有兴趣捕获异常。


场景是我有一个访问全局内存的对象

空间可通过多个线程访问。当共享资源被访问时,获取锁定然后释放。如果有人

试图访问一个不存在的变量,我仍然需要释放锁定的b / b
,以便其他线程可以继续工作,但是一个例外

应该提交给来电者。


无论如何,我在我的代码中玩弄了一些想法,并且在这次尝试中我是

试图嵌套尝试以至少确保访问变量

引发异常。就是这样,然后我试图提出

异常ValueError这样调用函数将获得

异常。这不行。似乎任何例外都会在尝试/最终中遇到b $ b。并且我不能得到例外来提高

而不是在此尝试之外提高它。是最好的

要做的事情是让异常机制设置某种类型的标志,我可以在终于期间查看
声明?


##代码##


类共享:

def __init __(自我):

self .__ userData = {}

self .__ mutex = threading.Lock()#lock object

def getVar(self,variableName ):

temp =无

错误= 0

self .__ mutex.acquire()#accessing共享词典

尝试:

试试:

temp = self .__ userData [variableName]

除了:

print"变量在共享

空间中不存在

提高ValueError

最后:

self .__ mutex。 release()

返回temp


def putVar(self,variableName,value):

self .__ mutex.acquire() #accessing共享词典

试试:

self .__ userData [variableName] = value

终于:

self。 __mutex.release()

返回


-


Carl J. Van Arsdall
< a href =mailto:cv ********* @ mvista.com> cv *** ******@mvista.com

构建和发布

MontaVista软件

Hey python people,

I''m interested in using the try/finally clause to ensure graceful
cleanup regardless of how a block of code exits. However, I still am
interested in capturing the exception.

The scenario is that I have an object that accesses a global memory
space accessible via multiple threads. When shared resources are
accessed a lock is acquired and then released. In the case that someone
tries to access a variable that doesn''t exist, I still need to release
the lock so that other threads can continue their work, but an exception
should be raised to the caller.

Anyhow, I was playing with ideas in my code, and in this attempt I
attempted to nest "try"s to at least make sure that accessing variables
was raising an exception. That''s the case, and then I attempt to raise
the exception "ValueError" so that the calling function will get the
exception. This doesn''t work though. It seems that any exceptions get
caught up in that "try/finally" and i can''t get the exception to raise
higher than that without raising it outside of this try. Is the best
thing to do to have the exception mechanism set some type of flag that I
can check during the "finally" statement?

##CODE##

class Shared:
def __init__(self):
self.__userData= {}
self.__mutex = threading.Lock() #lock object

def getVar(self, variableName):
temp = None
error = 0
self.__mutex.acquire() #accessing shared dictionary
try:
try:
temp = self.__userData[variableName]
except:
print "Variable doesn''t exist in shared
space"
raise ValueError
finally:
self.__mutex.release()
return temp

def putVar(self, variableName, value):
self.__mutex.acquire() #accessing shared dictionary
try:
self.__userData[variableName] = value
finally:
self.__mutex.release()
return

--

Carl J. Van Arsdall
cv*********@mvista.com
Build and Release
MontaVista Software

推荐答案

我想以下标准方法会有所帮助:


类MyLocker(对象):

def __init __(self,锁):

self.lock = lock

self.lock.acquire()


def __del __(self):

self.lock.release()


然后每当你需要锁定时:

templock = MyLocker(self .__ mutex )


del templock#将释放锁(前提是你没有创建一个

额外链接到这个对象)
I guess the following standard method will help :

class MyLocker(object):
def __init__(self, lock):
self.lock = lock
self.lock.acquire()

def __del__(self):
self.lock.release()

Then whenever you need to acquire a lock:
templock = MyLocker(self.__mutex)

del templock # will release the lock (provided you didn''t create an
extra link to this object)


取消您的第一个return语句。 putVar中的return语句不需要



Unindent your first return statement. The return statement in putVar is
not needed.


" Carl J. Van Arsdall" < CV ********* @ mvista.com>写道:
"Carl J. Van Arsdall" <cv*********@mvista.com> wrote:
类共享:
def __init __(self):
self .__ userData = {}
self .__ mutex = threading.Lock() #lock对象

def getVar(self,variableName):
temp =无
错误= 0
自我.__ mutex.acquire()#accessing共享词典尝试:
temp = self .__ userData [variableName]
除外:
print"变量在共享空间中不存在
引发ValueError
终于:
自我.__ mutex.release()
返回temp


对此有一些评论。


首先,有一个简单的除了:,这几乎总是一个坏主意,因为

捕获*每个*可能的异常。你想尽可能地捕获

异常(在这种情况下,我怀疑是'KeyError)。


其次,我''我不确定你的意图是从函数返回还是

在未知的variableName上引发异常。你不能两个都做!从 http://docs.python中引用

。 org / ref / try.html
..

当try子句发生异常时,暂时保存异常,执行finally子句,然后保存例外是重新提出的。如果finally子句引发另一个异常或执行
return或break语句,则保存的异常将丢失。
class Shared:
def __init__(self):
self.__userData= {}
self.__mutex = threading.Lock() #lock object

def getVar(self, variableName):
temp = None
error = 0
self.__mutex.acquire() #accessing shared dictionary
try:
try:
temp = self.__userData[variableName]
except:
print "Variable doesn''t exist in shared space"
raise ValueError
finally:
self.__mutex.release()
return temp
A few comments on this.

First, it''s almost always a bad idea to have a bare "except:", because that
catches *every* possible exception. You want to catch as specific an
exception as you can (in this case, I suspect that''s KeyError).

Second, I''m not sure if your intent was to return from the function or to
raise an exception on an unknown variableName. You can''t do both! Quoting
from http://docs.python.org/ref/try.html..
When an exception occurs in the try clause, the exception is temporarily
saved, the finally clause is executed, and then the saved exception is
re-raised. If the finally clause raises another exception or executes a
return or break statement, the saved exception is lost.




所以使用您发布的代码(从视线开始) ;我没有尝试过运行它,会发生什么




1)__ userData [variableName]引发KeyError


2)KeyError由内部try块捕获,而except块运行,

反过来引发ValueError


3) ValueError被外部try块捕获,finally块

运行,释放互斥锁,丢弃ValueError异常,并且

返回temp

4)调用getVar()的人将看到正常的返回值,返回值为

无(因为这是在getVar的第一行中设置为temp的值) )



so with the code you posted (from sight; I haven''t tried running it), what
will happen is:

1) __userData[variableName] raises KeyError

2) The KeyError is caught by the inner try block and the except block runs,
which in turn raises ValueError

3) The ValueError is caught by the outer try block and the finally block
runs, releasing the mutex, discarding the ValueError exception, and
returning temp

4) Whoever called getVar() will see a normal return, with a return value of
None (because that''s what temp was set to in the first line of getVar()


这篇关于使用try / finally处理异常的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆