重用try /函数中不同参数的除外

时间:2019-07-16 11:26:45

标签: python python-2.7

我正在尝试编写一个具有try / except块的5个参数的函数:

def clarifythis(dict1, dict2, dict3, dict4, dict5):
    try:
      Process dict1
    except Exception:
      Process dict1 differently

对于这5个参数,我应该为try / except写5个不同的块还是采用for循环:

def clarifythis(dict1, dict2, dict3, dict4, dict5):
    for i in (dict1, dict2, dict3, dict4, dict5):   
        try:
         Process i
        except Exception:
         Process i differently

提出问题的原因-从未使用try / except语句,因此可以澄清这一点。

1 个答案:

答案 0 :(得分:0)

取决于您想要的内容,并从一开始就考虑可以有哪些异常: 您还可以拥有类似的内容:

def clarifythis(dict1, dict2, dict3, dict4, dict5):
    try:
      Process dict1
    except Exception.name1:
      Process dict1 differently
    except Exception.name2:
      Process dict1 differently
    ...

并且根据我的经验,我没有遇到处理超过2-3个参数的问题,并且命令?如果您在此处添加for循环将有点难以理解,并查看此处发生了什么!