【发布时间】: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 语句可能引发e 或f,具体取决于发生的情况。显然无法替代
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,然后如果抛出它,您将得到内部异常。