[英]Can a finally block know if there was an exception
在Python程序中,我有以下結構的代碼:
try:
value = my_function(*args)
finally:
with some_context_manager:
do_something()
if 'value' in locals():
do_something_else(value)
但是'value' in locals()
構建中的'value' in locals()
感覺有點脆弱,我想知道是否有更好的方法來做到這一點。
我真正想要的是, finally
的代碼表現略有不同,具體取決於try
塊是否引發異常。 有沒有辦法知道是否引發了異常?
如果目標是“當異常被提出時,做一些不同的事情”,那么:
exception_raised = False
try:
value = my_function(*args)
except:
exception_raised = True
raise
finally:
with some_context_manager:
do_something()
if not exception_raised:
do_something_else(value)
現在,如果你有多個例外,你實際上做了什么,我建議:
completed_successfully = False
try:
value = my_function(*args)
else:
completed_successfully = True
finally:
with some_context_manager:
do_something()
if completed_sucessfully:
do_something_else(value)
以下是一些想法:
在嘗試嘗試之前設置值:
value = None
try:
value = my_function(*args)
finally:
with some_context_manager:
do_something()
if value is not None:
do_something_else(value)
或者,如果要根據異常類型設置值:
try:
value = my_function(*args)
except:
value = None
raise
finally:
with some_context_manager:
do_something()
if value is not None:
do_something_else(value)
將異常分配給except套件中的變量,然后在finally套件中使用它。
foo = False
try:
raise KeyError('foo not found')
except KeyError as e:
pprint(e)
foo = e
finally:
if foo:
print(foo)
else:
print('NO')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.