The python function returns None, is such a function irregular?
def fun (a,b):
try:
c = a/b
except Exception as ex:
logging.error(ex)
return c
ask the master to answer whether the return to this function is an irregular programming method, because the function may return "None", so how to better define this function in this case, for example?
when b is 0, you should not be able to get to return c. The program will exit. It seems that you should add a return, in front of except and add return None after the logging statement.
according to the logic of the program, when error occurs, it is not possible to return, only the output of logging, so the return is empty. You can adjust it like this:
def fun(a, b):
try:
c = a/b
except Exception as error:
logging.error(error)
c = 0
return c
The
exception should also retain an assignment, which is better at that time to avoid other problems in the later program. Your purpose should be to prevent the denominator from being 0, so again, you can do this:
def fun(a,b):
if b == 0:
logging.info('b=0')
res = 0
else:
res = a/b
return res
this depends on the situation. If I press your column, I think I can directly return an answer b
catch an exception when calling this function, because in this case, the return result of the function directly affects the later calculation. If it does not affect the later, you can handle the exception first, and then return None
def fun(a, b):
try:
c = a/b
except ZeroDivisionError:
logger.error(traceback.format_exc())
c = float('inf') if a > 0 else float('-inf')
finally:
return c
.