[英]Python: raise another exception in except block to catch later
I want something like this:我想要这样的东西:
trigger = True
try:
x = my_function() # This can raise IndexError
if x is None:
raise ValueError
except IndexError:
trigger = False
raise ValueError
except ValueError:
do_something()
I want trigger
to be False when IndexError is raised, and do_something()
to happen both if IndexError is raised, or the return value of my_function()
is None.我希望在引发 IndexError 时trigger
为 False,如果引发 IndexError 或my_function()
的返回值为 None,则do_something()
都会发生。 How can I achieve this?我怎样才能做到这一点?
One way to approach this is as follows:解决这个问题的一种方法如下:
trigger = True
try:
x = my_function() # This can raise IndexError
if x is None:
raise ValueError
except (ValueError, IndexError) as e:
if type(e) is IndexError:
trigger = False
do_something()
Otherwise, you may re-raise an error, but you will need nested try
block, and I assume you don't want that.否则,您可能会重新引发错误,但您将需要嵌套的try
块,我假设您不希望这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.