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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.