首页 > 技术文章 > 【Python】一个try/except/else/finally 组合使用的例子

jzsg 2019-08-05 15:48 原文

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()

推荐阅读