如何在Python中编写更干净的“ try catch”块?

时间:2019-04-12 08:15:58

标签: python try-catch

我有此代码:

def try_(things):
    try:
        return things
    except:
        return None

但是我希望这些调用产生以下结果:

try_([1,2,3][2]) -> 3

try_([1,2,3][4]) -> Error  (But I want it to return None)

1 个答案:

答案 0 :(得分:1)

您需要将索引作为参数传递:

def try_(things, index):
    try:
        return things[index]
    except:
        return None

这样称呼它:

try_([1,2,3], 2) -> 3

try_([1,2,3], 4) -> None