skylerl
skylerl

Reputation: 4180

Why is this except being called? - Python

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

Upvotes: 1

Views: 1117

Answers (2)

Kyle
Kyle

Reputation: 979

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.

Upvotes: 0

kriss
kriss

Reputation: 24177

The KeyError is probably raised by simplejson.loads and the offending key may really be None. Not enough context to say more. If you give the traceback as asked, it will help greatly.

Upvotes: 1

Related Questions