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?

May.22,2021

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
.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e52c57-451c8.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e52c57-451c8.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?