【Python】一个try/except/else/finally 组合使用的例子

UNDEFINED = object()

def divide_json(path):
    handle = open(path, 'r+')
    try:
        data = handle.read()
        op = json.load(data)
        value = (op['numerator'], op['denominator'])
    except ZeroDivisionError as e:
        return UNDEFINED
    else:
        op['result'] = value
        result = json.dumps(op)
        handle.seek(0)
        handle.write(result)
        return value
    finally:
        handle.close()

你可能感兴趣的:(【Python】一个try/except/else/finally 组合使用的例子)