[英]How to re-catch already caught exception in Python?
我有一個類似於以下代碼:
try:
something()
except DerivedException as e:
if e.field1 == 'abc':
handle(e)
else:
# re-raise with catch in the next section!
except BaseException as e:
do_some_stuff(e)
DerivedException
是從BaseException
派生的。
所以,就像代碼中提到的注釋一樣 - 我想從第一個except
section except
重新引發異常,並在第二個except
section except
再次捕獲它。
怎么做?
Python的語法提供沒有辦法從一個繼續except
塊地在同一個try
。 你可以得到的最接近的是兩個try
:
try:
try:
whatever()
except Whatever as e:
if dont_want_to_handle(e):
raise
handle(e)
except BroaderCategory as e:
handle_differently(e)
就個人而言,我會使用except
塊except
一個並手動執行調度:
try:
whatever()
except BroaderCategory as e:
if isinstance(e, SpecificType) and other_checks(e):
do_one_thing()
else:
do_something_else()
這是你想要的?
{ ~ } » python
>>> try:
... try:
... raise Exception("foobar")
... except Exception as e:
... raise e
... except Exception as f:
... print "hi"
...
hi
您只需使用raise關鍵字來引發剛剛捕獲的錯誤。
try:
try:
something()
except DerivedException as e:
if e.field1 == 'abc':
handle(e)
else:
raise
except BaseException as e:
do_some_stuff(e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.