Issue
I have below try-except to catch JSON parse errors:
with open(json_file) as j:
try:
json_config = json.load(j)
except ValueError as e:
raise Exception('Invalid json: {}'.format(e))
Why is During handling of the above exception, another exception occurred
printed out, and how do I resolve it?
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 103 column 9 (char 1093)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
<....>
raise Exception('Invalid json: {}'.format(e))
Exception: Invalid json: Expecting ',' delimiter: line 103 column 9 (char 1093)
Solution
Currently, you are having an issue with raising the ValueError
exception inside another caught exception. The reasoning for this solution doesn't make much sense to me, but if you change it.
raise Exception('Invalid json: {}'.format(e))
To
raise Exception('Invalid json: {}'.format(e)) from None
Making your end code.
with open(json_file) as j:
try:
json_config = json.load(j)
except ValueError as e:
raise Exception('Invalid json: {}'.format(e)) from None
You should get the desired result of catching an exception.
e.g.
>>> foo = {}
>>> try:
... var = foo['bar']
... except KeyError:
... raise KeyError('No key bar in dict foo') from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
KeyError: 'No key bar in dict foo'
Sorry, I can't explain why this works precisely, but it seems to do the trick.
UPDATE: It looks like there's a PEP doc explaining how to suppress exceptions inside exception warnings.
Answered By - Skam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.