如何在python中测试if语句中的异常?
我想写一个函数来报告来自另一个函数的不同结果 这些结果中有一些例外,但我无法将它们转换为if语句 例如: 如果f(x)引发ValueError,则我的函数必须返回字符串 “Value”如果f(x)引发TypeError,则我的函数必须返回一个 字符串类型 但我不知道如何在Python中实现这一点。有人能帮帮我吗 我的代码如下:-如何在python中测试if语句中的异常?,python,function,exception,if-statement,Python,Function,Exception,If Statement,我想写一个函数来报告来自另一个函数的不同结果 这些结果中有一些例外,但我无法将它们转换为if语句 例如: 如果f(x)引发ValueError,则我的函数必须返回字符串 “Value”如果f(x)引发TypeError,则我的函数必须返回一个 字符串类型 但我不知道如何在Python中实现这一点。有人能帮帮我吗 我的代码如下:- def reporter(f,x): if f(x) is ValueError(): return 'Value' elif
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
构造中,如
try:
f(x)
except ValueError as e:
return "Value"
except E20ddException as e:
return "E20dd"
函数本身不返回异常,异常在外部捕获 您必须在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
是处理异常的唯一方法。啊,明白了!谢谢!
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'