简体   繁体   English

为什么这除了被称为? -Python

[英]Why is this except being called? - Python

I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. 我有一种方法可以检查JSON负载以获取JSON解码错误和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 . 出于某种原因,带有KeyErrorexcept语句将被调用,但随后显示实际上没有KeyError因为对象为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

The KeyError is probably raised by simplejson.loads and the offending key may really be None . KeyError可能是由simplejson.loads引发的,并且有问题的键实际上可能是None Not enough context to say more. 没有足够的上下文可以说更多。 If you give the traceback as asked, it will help greatly. 如果您按要求进行回溯,将大有帮助。

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. 查看回溯应该可以告诉您引发异常的模块。您可能还需要考虑使用ipdb手动来回调试调试此类将来的问题。 Further more, you should inherit from Python's Exception class so you have more control over your own code by raising and excepting. 此外,您应该继承自Python的Exception类,以便通过引发和排除对自己的代码进行更多控制。

Utilizing Python's getattr and setattr functions help a lot too: 利用Python的getattr和setattr函数也有很多帮助:

Using getattr on test_data will let you know when to raise your custom exception in the event that that None is returned. 在test_data上使用getattr将使您知道何时返回None的情况下何时引发自定义异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM