我要求我必须在方法“meth(a)”中引发异常,只有我能实现的方法是将字典“a”声明为某个值,使得a.get('v',0)提出异常
def meth(a):
if isinstance(a, dict):
return a.get('v', 0)# I have to raise an exception from here
return 0
a = {} #I have to give some value into this dictionary so that my meth(a) raises an exception'''
import re
import sys
import traceback
try:
meth(a)
except Exception:
print("meth exception!")
sys.exit()
raise
else:
sys.stderr.write("meth has no exception")
答案 0 :(得分:2)
取决于声明字典“a”到某个值的含义。您可以创建自己的继承自dict
的类,以便isinstance
测试工作并实现不友好的get
。
class MyDict(dict):
def get(self, name, default=None):
raise NameError("No way am I getting you a value. "
"What kind of a dict do you think I am?")
a = MyDict()
其余的只是你的程序...