【问题标题】:Handling multiple Try/Except statements处理多个 Try/Except 语句
【发布时间】:2018-08-08 08:26:23
【问题描述】:

我正在使用多个 try/except 块将数据帧(比如数据)的值分配给 3 个变量(比如 b、c、d)如果位置索引器超出,我想处理 IndexErrors界外。我目前正在做的如下图所示:

b,c,d=None,None,None
try:
    b=data.iloc[1,1]
except:
    pass
try:
    c=data.iloc[2,1]
except:
    pass
try:
    d=data.iloc[0,2]
except:
    pass

我想知道是否有更好的方法,例如函数 try_except() 或其他东西,以便我可以使用它,如下所示:

try_except(b=data.iloc[1,1])
try_except(c=data.iloc[2,1])
try_except(d=data.iloc[0,2])

【问题讨论】:

    标签: python exception error-handling exception-handling


    【解决方案1】:

    您可以只编写一个执行查找并捕获异常的函数,但顺便提一下,except: pass 可能是个坏主意。您应该更具体地处理错误。

    def safe_get(container, i, j):
        try:
            return container[i,j]
        except IndexError: # or whatever specific error you're dealing with
            return None
    
    b = safe_get(data.iloc, 1, 1)
    c = safe_get(data.iloc, 2, 1)
    d = safe_get(data.iloc, 0, 2)
    

    【讨论】:

      猜你喜欢
      • 2011-09-29
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2019-12-31
      • 2018-02-24
      • 1970-01-01
      • 2021-08-28
      相关资源
      最近更新 更多