use*_*023 3 python if-statement exception function
我想编写一个函数来报告来自另一个函数的不同结果,这些结果中有一些例外,但我无法将它们转换为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'
Run Code Online (Sandbox Code Playgroud)
Roh*_*ain 13
你必须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'
Run Code Online (Sandbox Code Playgroud)