我有类似以下的代码:
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
- 部分内部重新引发异常并在第二个except
部分内再次捕获它。
怎么做?
答案 0 :(得分:7)
Python的语法无法在同一个except
上从一个try
块继续到另一个块。最接近的是两个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)
就个人而言,我会使用一个except
块并手动执行调度:
try:
whatever()
except BroaderCategory as e:
if isinstance(e, SpecificType) and other_checks(e):
do_one_thing()
else:
do_something_else()
答案 1 :(得分:0)
这是你在找什么?
{ ~ } » python
>>> try:
... try:
... raise Exception("foobar")
... except Exception as e:
... raise e
... except Exception as f:
... print "hi"
...
hi
答案 2 :(得分:-1)
您只需使用raise关键字来引发刚刚捕获的错误。
try:
try:
something()
except DerivedException as e:
if e.field1 == 'abc':
handle(e)
else:
raise
except BaseException as e:
do_some_stuff(e)