How do I catch an already caught exception in Python?
I have some 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 it DerivedException
comes from BaseException
.
So, just like the comment in the code is mentioned - I want to re-throw the exception from within the first section except
and catch it again in the second section except
.
How to do it?
source to share
Python syntax does not allow you to go from one block except
to another in the same try
. The closest you can get is two try
s:
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 would use one block except
and manually submit:
try:
whatever()
except BroaderCategory as e:
if isinstance(e, SpecificType) and other_checks(e):
do_one_thing()
else:
do_something_else()
source to share