我在想,您是否可以重新引发(特定的)异常,并让稍后(一般)捕获它,除非在相同的尝试-除外。例如,我想使用特定的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以外的上下文之外,引发重新引发异常。用什么方式来写这篇文章,才能得到想要的例外“跌落”行为呢?
(我知道有一个提议的‘条件’,但没有实现,这可以解决这个问题)
发布于 2018-04-20 17:56:54
如果你最终想让它抓住一切,那就让它去做。先抓,再筛。;)
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发布于 2015-10-19 14:58:18
我不是编写nested的专家,但我认为一种明显的方法(如果您知道您期望的是一种特定的异常),将是使用嵌套的异常处理:
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我在你的评论中知道,你不想要嵌套别人的--我不知道嵌套异常处理在你的书中是否有那么糟糕,但至少你可以避免代码重复。
发布于 2016-02-10 23:46:47
因此,我在这里做同样的工作,在审查了可用的解决方案之后,我将继续捕获父异常,然后测试具体情况。在我的例子中,我正在使用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 stuffhttps://stackoverflow.com/questions/33217472
复制相似问题