Effective Python 读书笔记: 第14条: 尽量用异常来表示特殊情况,而不要返回None

# -*- encoding: utf-8 -*-

import os

'''
第14条: 尽量用异常来表示特殊情况, 而不要返回None

关键:
1 函数返回None
缺点: 会使调用它的人写出错误的代码,因为None, 0, 空字符串都会被
条件表达式评估为False
解决方法:
1) 把返回值拆成两部分,放到二元组,第一个元素表示是否操作成功;
第二个元素是运算结果
2) 发生异常,直接抛给调用者


参考:
Effectiv Python 编写高质量Python代码的59个有效方法


'''

def divide(a, b):
    try:
        return True, a / b
    except Exception:
        return False, None


def divideException(a, b):
    try:
        return a / b
    except Exception:
        raise Exception('Invalid error')


def useDivide(a, b):
    isOk, result = divide(a, b)
    if not isOk:
        print "error"
    else:
        print "ok, result: {result}".format(
            result=result
        )


def process():
    a = 0
    b = 3
    useDivide(a, b)
    a = 3
    b = 0
    try:
        result = divideException(a, b)
        print result
    except Exception:
        print "invalid inputs"

if __name__ == "__main__":
    process() 

猜你喜欢

转载自blog.csdn.net/qingyuanluofeng/article/details/88832277