我正在尝试对错误进行一些清理,然后重新引发导致错误的异常:
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
因为原始追溯将被销毁。对我来说,内部异常比外部异常更重要,那么有没有办法专门提出异常?
答案 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')
随机打印Hello
或Goodbye
。