over 3 years ago

Take Advantage of Each Block in try/except/else/finally

這條款講的是要搞清楚 try/except/else/finally 這四種個字的使用時機。
善用 else 的好處是可以減少 try 區塊的程式碼,讓程式的意圖更加明顯。

def load_json_key(data, key):
    try:
        result_dict = json.loads(data)  # May raise ValueError

    except ValueError as e:
        raise KeyError from e
    else:
        return result_dict[key]         # May raise KeyError

通通一起用:

UNDEFINED = object()
def divide_json(path):
    handle = open(path, 'r+')   # May raise IOError

    try:
        data = handle.read()    # May raise UnicodeDecodeError

        op = json.loads(data)   # May raise ValueError

        value = (
            op['numerator'] /
            op['denominator'])  # May raise ZeroDivisionError

    except ZeroDivisionError as e:
        return UNDEFINED
    else:
        op['result'] = value
        result = json.dumps(op)
        handle.seek(0)
        handle.write(result)    # May raise IOError

        return value
    finally:
        handle.close()          # Always runs
← Effective Python 心得筆記: Item 12 Effective Python 心得筆記: Item 14 →
 
comments powered by Disqus