Python 'except' 失败
Python 'except' fall-through
我想知道您是否可以重新引发一个(特定的)捕获的异常,并让它在同一个 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
但是,这不起作用:raise 在 try-except 的上下文之外重新引发异常。
编写此代码以获得所需异常 'fall-through' 行为的 pythonic 方式是什么?
(我知道有一个提议 'conditional except' 没有实施,这本来可以解决这个问题)
我不是用 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
我在你的评论中知道你不想要嵌套的 else -- 我不知道嵌套的异常处理是否和你的书中一样糟糕,但至少你可以避免代码重复。
所以,我在这里做同样的工作,在查看了可用的解决方案之后,我将继续捕获父异常,然后测试细节。就我而言,我正在使用 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
如果您最终希望它捕获所有内容,请让它执行此操作。先抓,后筛。 ;)
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
我想知道您是否可以重新引发一个(特定的)捕获的异常,并让它在同一个 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
但是,这不起作用:raise 在 try-except 的上下文之外重新引发异常。 编写此代码以获得所需异常 'fall-through' 行为的 pythonic 方式是什么?
(我知道有一个提议 'conditional except' 没有实施,这本来可以解决这个问题)
我不是用 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
我在你的评论中知道你不想要嵌套的 else -- 我不知道嵌套的异常处理是否和你的书中一样糟糕,但至少你可以避免代码重复。
所以,我在这里做同样的工作,在查看了可用的解决方案之后,我将继续捕获父异常,然后测试细节。就我而言,我正在使用 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
如果您最终希望它捕获所有内容,请让它执行此操作。先抓,后筛。 ;)
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