加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:29:42 所属栏目:Python 来源:网络整理
导读:我想写一个函数来报告另一个函数的不同结果 这些结果中有一些例外,但我无法将它们转换为if语句 例如: if f(x) raise a ValueError,then my function has to return a string ‘Value’ if f(x) raise a TypeError,then my function has to return a string
我想写一个函数来报告另一个函数的不同结果
这些结果中有一些例外,但我无法将它们转换为if语句

例如:

if f(x) raise a ValueError,then my function has to return a string
‘Value’ if f(x) raise a TypeError,then my function has to return a
string ‘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'

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读