gpt4 book ai didi

python-2.7 - Python 'except' 失败

转载 作者:行者123 更新时间:2023-12-04 02:20:56 25 4
gpt4 key购买 nike

我想知道您是否可以重新引发(特定)捕获的异常,并在同一个 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 的上下文之外重新引发异常。
编写此代码以获得所需的异常“通过”行为的pythonic 方式是什么?

(我知道有一个提议的“条件除外”没有实现,这可以解决这个问题)

最佳答案

如果您最终希望它捕获所有内容,请让它这样做。先抓,后筛。 ;)

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

关于python-2.7 - Python 'except' 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33217472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com