Python:如何避免异常捕获中的代码重复? [英] Python: how to avoid code duplication in exception catching?
问题描述
try:
page = urlopen(request)
除了URLError,err:
logger.error(错误ocurred%s,err)
除了HTTPError,err:
logger.error(发生错误%s,错误)
logger.error(错误消息:%s,err.read())
在这个例子中,我想避免第一个logger.error调用的重复。给定URLError是HTTPError的父级,可以这样做:
除了URLError,err:
logger.error (发生错误%s,err)
try:
raise err
除了HTTPError,err:
#专用于http错误
logger.error(错误信息:%s,err.read())
除了:
pass
另一种方法是使用isinstance例如。如果URLError和HTTPError不会在继承链中:
except(URLError,HTTPError),err:
logger.error(发生错误%s,err)
如果isinstance(err,HTTPError):
logger.error(错误消息:%s,err.read())
我应该选择哪一个,还有另一个更好的方法吗?
我认为你的第三个例子是最好的解决方案。
- 这是最短的版本
- 它可以避免重复
- 很清楚阅读和轻松关注,与第二个版本。
您可能需要使用除FooError之外的较新的作为错误
语法,但是,如果你在Python 2.6或更高版本。
另外,在你的例子中,第一个版本不是很正确,因为 URLError
处理程序已经捕获了 HTTPError
,所以除了HTTPError 部分之外的不能达到。你必须切换两个
,除了
之外。另一个不用这个的原因。
What is a good pattern to avoid code duplication when dealing with different exception types in Python, eg. I want to treat URLError and HTTPError simlar but not quite:
try:
page = urlopen(request)
except URLError, err:
logger.error("An error ocurred %s", err)
except HTTPError, err:
logger.error("An error occured %s", err)
logger.error("Error message: %s", err.read())
In this example, I would like to avoid the duplication of the first logger.error call. Given URLError is the parent of HTTPError one could do something like this:
except URLError, err:
logger.error("An error occurred %s", err)
try:
raise err
except HTTPError, err:
# specialization for http errors
logger.error("Error message: %s", err.read())
except:
pass
Another approach would be to use isinstance eg. if URLError and HTTPError would not be in a chain of inheritance:
except (URLError, HTTPError), err:
logger.error("An error occured %s", err)
if isinstance(err, HTTPError):
logger.error("Error message: %s", err.read())
Which one should I prefer, is there another better approach?
I think that your third example is the best solution.
- It's the shortest version
- It avoids duplication
- It is clear to read and easy to follow, much unlike the second version.
You might want to use the newer except FooError as err
syntax, though, if you're on Python 2.6 or higher.
Also, in your example, the first version isn't quite correct since the URLError
handler already catches the HTTPError
, so the except HTTPError
part is never reached. You'd have to switch the two except
s around. Another reason not to use this.
这篇关于Python:如何避免异常捕获中的代码重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!