over 3 years ago

Prefer Exceptions to Returning None

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None

回傳 None 容易造成誤用,下面的程式分不出 0 和 None

x, y = 0, 5
result = divide(x, y)
if not result:
    print('Invalid inputs')  # This is wrong!

else:
    assert False

丟 exception:

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError as e:
        raise ValueError('Invalid inputs') from e

使用該函式的人須注意可能有 ValueError,要做相關處理,不易出錯。

← Effective Python 心得筆記: Item 13 Effective Python 心得筆記: Item 15 →
 
comments powered by Disqus