【问题标题】:How do I test for exceptions in if-statements in python?如何在 python 中的 if 语句中测试异常?
【发布时间】:2013-01-25 06:56:47
【问题描述】:

我想写一个函数来报告另一个函数的不同结果 这些结果中有一些例外,但我无法将它们转换为 if 语句

示例:

如果 f(x) 引发 ValueError,那么我的函数必须返回一个字符串 'Value' 如果 f(x) 引发 TypeError,那么我的函数必须返回一个 字符串'类型

但我不知道如何在 Python 中执行此操作。谁能帮帮我。

我的代码是这样的:-

def reporter(f,x):    

    if f(x) is ValueError():
        return 'Value'
    elif f(x) is E2OddException():
        return  'E2Odd'
    elif f(x) is E2Exception("New Yorker"):
        return 'E2'
    elif f(x) is None:
        return 'no problem'
    else:
        return 'generic'

【问题讨论】:

  • 你为什么大喊大叫? .....说真的,请不要使用全大写。它很难阅读,让我们的(精神)耳朵受伤。
  • 对此我感到非常抱歉..我只是对此感到疯狂。我的作业实际上明天就要交了。

标签: python function exception if-statement


【解决方案1】:

你有 try-except 来处理 Python 中的异常:-

def reporter(f,x): 
    try:
        if f(x):  
            # f(x) is not None and not throw any exception. Your last case
            return "Generic"
        # f(x) is `None`
        return "No Problem"
    except ValueError:
        return 'Value'
    except TypeError:
        return 'Type'
    except E2OddException:
        return 'E2Odd'

【讨论】:

  • 谢谢!但是我在我的课程中没有学到这一点。所以也许我不能使用它。
  • @user2010023 try-except 是处理异常的唯一方法。
  • 啊,明白了!非常感谢!
【解决方案2】:
def reporter(f,x):    
    try:
        if f(x) is None:
            return 'no problem'
        else:
            return 'generic'
    except ValueError:
        return 'Value'
    except E2OddException:
        return  'E2Odd'
    except E2Exception:
        return 'E2'

【讨论】:

    【解决方案3】:

    您将函数调用放在 try-except 结构中,例如

    try:
        f(x)
    except ValueError as e:
        return "Value"
    except E20ddException as e:
        return "E20dd"
    

    函数本身不返回异常,异常被外部捕获。

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 2016-04-21
      • 1970-01-01
      • 2021-06-10
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多