[英]How to re-catch already caught exception in Python?
I have a code similar to the following: 我有一个类似于以下代码:
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)
Where DerivedException
is derived from BaseException
. DerivedException
是从BaseException
派生的。
So, like the comment in the code mentions - I want to re-raise the exception from inside of the first except
-section and catch it again inside the second except
-section. 所以,就像代码中提到的注释一样 - 我想从第一个except
section except
重新引发异常,并在第二个except
section except
再次捕获它。
How to do that? 怎么做?
Python's syntax provides no way to continue from one except
block to another on the same try
. Python的语法提供没有办法从一个继续except
块地在同一个try
。 The closest you can get is with two try
s: 你可以得到的最接近的是两个try
:
try:
try:
whatever()
except Whatever as e:
if dont_want_to_handle(e):
raise
handle(e)
except BroaderCategory as e:
handle_differently(e)
Personally, I'd use one except
block and do the dispatch manually: 就个人而言,我会使用except
块except
一个并手动执行调度:
try:
whatever()
except BroaderCategory as e:
if isinstance(e, SpecificType) and other_checks(e):
do_one_thing()
else:
do_something_else()
Is this what you are looking for? 这是你想要的?
{ ~ } » python
>>> try:
... try:
... raise Exception("foobar")
... except Exception as e:
... raise e
... except Exception as f:
... print "hi"
...
hi
You just use the raise keyword alone to raise the error that was just caught. 您只需使用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.