Python'除了'堕落

Ove*_*lex 10 exception-handling try-catch python-2.7

我想知道你是否可以重新提出一个(特定的)捕获异常并让它被后来(普通)捕获,除非在同一个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
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用:加注在try-except的上下文之外重新引发异常.写这个的pythonic方式是什么,以获得所需的异常"跌倒"行为?

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

Bac*_*sau 6

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

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
Run Code Online (Sandbox Code Playgroud)