The following example is very simple. I want to execute map() with a function which can raise Exception. It will be more clearly with an example :
number_list = range(-2,8)
def one_divide_by(n):
return 1/n
try:
for number, divide in zip(number_list, map(one_divide_by, number_list)):
print("%d : %f" % (number, divide))
except ZeroDivisionError:
# Execution is stopped. I want to continue mapping
pass
When I execute this code I get :
-2 : -0.500000
-1 : -1.000000
It's due to the 0 in my list. I don't want remove this 0 (because in real case I can't know first if I will get Exception). Do you know how to continue mapping after the exception ?
you could catch the exception in your function (instead of in the for
loop) and return None
(or whatever you choose) if ZeroDivisionError
is raised:
def one_divide_by(n):
try:
return 1/n
except ZeroDivisionError:
return None
if you choose to return None
you need to adapt your format string; None
can not be formatted with %f
.
other values you could return (and that would be compatible with your string formatting) are float('inf')
(or float('-inf')
depending on the sign of your numerator) or float('nan')
- "infinity" or "not a number".
here you will find some of the caveats of using float('inf')
.
You can move the try/except
block inside the function. Example -
def one_divide_by(n):
try:
return 1/n
except ZeroDivisionError:
return 0 #or some other default value.
And then call this normally, without a try/except block -
for number, divide in zip(number_list, map(one_divide_by, number_list)):
print("%d : %f" % (number, divide))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With