I think that try except(as in the Cyber answer), as a rule, a better way (and more pythonic: it's better to ask for forgiveness than ask permission!), But here's another:
def safe_div(x,y):
if y == 0:
return 0
return x / y
One argument in favor of this, however, is that if you expect it to ZeroDivisionErrorhappen often, checking for 0 denominators will be much faster (this is python 3):
import time
def timing(func):
def wrap(f):
time1 = time.time()
ret = func(f)
time2 = time.time()
print('%s function took %0.3f ms' % (f.__name__, int((time2-time1)*1000.0)))
return ret
return wrap
def safe_div(x,y):
if y==0: return 0
return x/y
def try_div(x,y):
try: return x/y
except ZeroDivisionError: return 0
@timing
def test_many_errors(f):
print("Results for lots of caught errors:")
for i in range(1000000):
f(i,0)
@timing
def test_few_errors(f):
print("Results for no caught errors:")
for i in range(1000000):
f(i,1)
test_many_errors(safe_div)
test_many_errors(try_div)
test_few_errors(safe_div)
test_few_errors(try_div)
Conclusion:
Results for lots of caught errors:
safe_div function took 185.000 ms
Results for lots of caught errors:
try_div function took 727.000 ms
Results for no caught errors:
safe_div function took 223.000 ms
Results for no caught errors:
try_div function took 205.000 ms
, try except 3-4 ( , ) ; : 3-4 , . , if, (10% ), ( , ) .