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

8 投票
3 回答
54309 浏览
提问于 2025-04-17 13:37

我想写一个函数,用来报告另一个函数的不同结果。结果中有一些例外情况,但我无法把它们转换成if语句。

举个例子:

如果 f(x) 抛出一个 ValueError,那我的函数就得返回一个字符串 'Value';如果 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'

3 个回答

0

你可以把你的函数调用放在一个 try-except 结构里,像这样:

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

这个函数本身并不会返回错误,错误是在外面被捕捉到的。

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'

这段代码是用来做某些操作的,但具体的功能和效果需要根据上下文来理解。代码块通常包含了一些编程指令,可能涉及到变量、函数或者其他编程概念。

如果你看到这样的代码,首先要明白它是用来解决什么问题的。每一行代码都有它的作用,可能是计算、存储数据或者控制程序的流程。

在学习编程时,遇到代码块是很正常的事情。可以尝试逐行分析,看看每一部分是如何工作的,慢慢你就会对这些代码有更深的理解。

记住,编程就像学习一种新的语言,刚开始可能会觉得难,但多练习就会变得越来越容易。

18

在Python中,你可以使用try-except来处理错误和异常:

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'

撰写回答