如何在python中测试if语句中的异常?

时间:2013-01-25 06:56:47

标签: python function exception if-statement

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

示例:

  

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

但我不知道如何在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'

3 个答案:

答案 0 :(得分:12)

你有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'

答案 1 :(得分:1)

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'

答案 2 :(得分:0)

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

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

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