我想知道你是否可以重新引发一个(特定的)捕获的异常并让它被一个稍后的(一般)捕获,除了在同一个try-except中。作为一个例子,我想用特定的IOError做一些事情,但如果它不是预期的IOError,那么异常应该像任何其他错误一样处理。我最初的尝试:
try:
raise IOError()
except IOError as ioerr:
if ioerr.errno == errno.ENOENT:
# do something with the expected err
else:
# continue with the try-except - should be handled like any other error
raise
except Exception as ex:
# general error handling code
但是,这并不起作用:加注会在try-except的上下文之外重新引发异常。 写这篇文章的pythonic方法是什么,以获得所需的异常' fall-through'行为?
(我知道有一个提议的条件除了'没有实施,这可以解决这个问题)
答案 0 :(得分:1)
我不是编写python的专家,但我认为一种明显的方法(如果你知道你期望一种特殊的异常),就是使用嵌套异常处理:
try:
try:
raise IOError()
except IOError as ioerr:
if ioerr.errno == errno.ENOENT:
# do something with the expected err
else:
# pass this on to higher up exception handling
raise
except Exception as ex:
# general error handling code
我在你的评论中知道你不想要嵌套的别人 - 我不知道嵌套的异常处理在你的书中是否同样糟糕,但至少你可以避免代码重复。
答案 1 :(得分:1)
如果你最终希望它能抓住一切,那就去做吧。首先捕获,稍后筛选。 ;)
try:
raise IOError()
except Exception as ex:
if isinstance(ex, IOError) and ex.errno == errno.ENOENT:
# do something with the expected err
# do the rest
答案 2 :(得分:0)
所以,我在这里工作一样,在查看了可用的解决方案后,我将继续捕获父异常,然后测试具体细节。就我而言,我正在使用dns模块。
try:
answer = self._resolver.query(name, 'NS')
except dns.exception.DNSException, e: #Superclass of exceptions tested for
if isinstance(e, dns.resolver.NXDOMAIN):
#Do Stuff
elif isinstance(e, dns.resolver.NoAnswer):
# Do other stuff
else:
# Do default stuff