【问题标题】:Is there a way to write the same try-except for multiple lines of code without hardcoding? python有没有办法编写相同的尝试——除了多行代码而无需硬编码? Python
【发布时间】:2014-04-22 07:13:14
【问题描述】:

我有多个函数可能会返回None

do_something()do_something2()do_something3()

为了克服无类型错误,我必须从代​​码的另一部分硬编码try-except

try:
  x = do_other_things(do_something())
except someError: # because of None Type return
  x = None

try:
  y = do_other_things(do_something2())
except someError: # because of None Type return
  y = None

有什么方法可以将相同的try-except 应用于不同的代码行/不同的函数调用?

【问题讨论】:

    标签: python error-handling try-catch except hardcode


    【解决方案1】:

    如果您正在测试相同的异常类型,则可以将 try/except 块包装到一个函数中,该函数接受其他函数和参数列表作为参数。

     def try_except(myFunction, *params):
         try:
             return myFunction(*params)
         except ValueError as e:
             return None
         except TypeError as e:
             return None
    

    【讨论】:

    • 为此,您需要在函数体中也包含星号 (*):return myFunction(*params)
    【解决方案2】:

    我不是 python 专家,但我可以换一种方式思考。

    创建一个函数数组并循环调用它们:

    listOfFuncs = [do_something,do_something2,do_something3]
    
    results = []*len(listOfFuncs)
    for index, func in enumerate(listOfFuncs):
        try:
            results[index] = do_other_things(func())
        except someError:
            results[index] = None
    

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多