繁体   English   中英

使用额外的try-except块重新编译异常

[英]Reraise Exception with additional try-except block

我试图在错误上做一些清理,然后重新引发导致错误的异常:

try:
    with open(filename, 'wb') as f:
        raise ValueError('something happened')              # do something that could fail
except Exception as e:                                      # Clean up in case of any error
    try:
        os.remove(filename)
    except Exception as f:                                    # Cleaning up could fail too, but we are not interested in that one
        pass
    raise                                                   # This re-raises `e` if file deletion was OK
                                                            # but re-raises `f` if file deletion was not OK

根据发生的情况,最后一次raise声明可能会提高ef 显然不可能取代

raise

raise e

因为原始追溯将被销毁。 对我来说,内部异常比外部异常更重要,那么有没有办法专门提出异常?

不确定嵌套异常的问题是什么:

try:
    raise ValueError('something happened')
except Exception as e:
    try:
        if random.randint(0,1):
            raise OSError('something else happened')
    except OSError:
        raise
    raise

例如:

import random
try:
    try:
        raise ValueError('something happened')
    except Exception:
        try:
            if random.randint(0,1):
                raise OSError('something else happened')
        except OSError:
            raise
        raise
except OSError:
    print('Hello')
except ValueError:
    print('Goodbye')

随机打印HelloGoodbye

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM