【问题标题】:Reraise Exception with additional try-except block使用额外的 try-except 块重新引发异常
【发布时间】:2016-12-30 14:45:46
【问题描述】:

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

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..except..finally区块。
  • 有什么问题?如果你得到一个 OSError 你会得到一个嵌套异常 - During handling of the above exception (ValueError), another exception occurred: (OSError)
  • 不,try..except..finally 在这里不起作用。 @AChampion 我想重新引发内部异常,无论是否抛出外部异常。
  • 为什么finally 不起作用?如果外部已经被提升,您当前的方法只会抛出内部。
  • 然后我很困惑'我想重新引发内部异常,无论外部异常是否被抛出。只需将pass 替换为raise,然后如果抛出它,您将得到内部异常。

标签: python exception


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2013-08-13
    • 1970-01-01
    • 2016-02-12
    • 2010-10-22
    • 1970-01-01
    • 2021-08-19
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多