我如何测试python中的if statement的例外?

问题描述 投票:0回答:3
我想编写一个函数来报告其他功能的不同结果 这些结果中有一些例外

示例:

如果f(x)提出一个值,然后我的功能必须返回字符串 “值”如果f(x)提出了typeError,则我的功能必须返回 字符串'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'

您有python中的例外:-
python function exception if-statement
3个回答
18
投票

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'

您将您的函数调用放在
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
投票

DEF记者(F,X):

尝试:
如果f(x)无:
返回“没问题”
别的:
返回“通用”
除了Valueerror:
返回'值'
除了e2oddexception:
返回'e2odd'
除了E2Sception:
返回'e2'


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.