除了被调用之外,为什么会这样呢? - Python
我有一个方法可以检查 JSON 负载是否存在 JSON 解码错误和 KeyErrors。由于某种原因,带有 KeyError
的 except
语句被调用,但随后显示实际上没有 KeyError
因为对象是 <代码>无。这是代码:
try:
test_data = simplejson.loads(self.raw_data) # Loads the data in a dict to test for the right fields
test_data["test"]
except simplejson.decoder.JSONDecodeError as jsonErr:
print 'JSON Malform Error: ', jsonErr
pass
return False
except KeyError as keyErr:
print 'JSON Validation Error: ', keyErr
pass
I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. For some reason, the except
statement with the KeyError
is getting called, but then shows there was in fact, no KeyError
as the object is None
. Here is the code:
try:
test_data = simplejson.loads(self.raw_data) # Loads the data in a dict to test for the right fields
test_data["test"]
except simplejson.decoder.JSONDecodeError as jsonErr:
print 'JSON Malform Error: ', jsonErr
pass
return False
except KeyError as keyErr:
print 'JSON Validation Error: ', keyErr
pass
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
KeyError 可能是由
simplejson.loads
引发的,并且有问题的密钥可能实际上是None
。没有足够的上下文来说明更多。如果您按照要求提供回溯,将会有很大帮助。The KeyError is probably raised by
simplejson.loads
and the offending key may really beNone
. Not enough context to say more. If you give the traceback as asked, it will help greatly.查看回溯应该会告诉您在哪个模块中引发了异常。您可能还需要考虑使用 ipdb 手动来回调试类似这样的未来问题。此外,您应该继承 Python 的 Exception 类,这样您就可以通过引发和异常更好地控制自己的代码。
利用 Python 的 getattr 和 setattr 函数也有很大帮助:
在 test_data 上使用 getattr 将让如果返回 None ,您知道何时引发自定义异常。
Looking through the traceback should tell you what module the exception was raised in. You might also want to consider using ipdb to manually step back and forth to debug future issues like this. Further more, you should inherit from Python's Exception class so you have more control over your own code by raising and excepting.
Utilizing Python's getattr and setattr functions help a lot too:
Using getattr on test_data will let you know when to raise your custom exception in the event that that None is returned.