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

时间:2016-12-30 14:45:47

标签: python exception

我正在尝试对错误进行一些清理,然后重新引发导致错误的异常:

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

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

1 个答案:

答案 0 :(得分:0)

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

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