Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

python - During handling of the above exception, another exception occurred

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)
question from:https://stackoverflow.com/questions/52725278/during-handling-of-the-above-exception-another-exception-occurred

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Currently, you 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

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 give you an explanation why this works specifically but it seems to do the trick.

UPDATE: Looks like there's a PEP doc explaining how to suppress these exception inside exception warnings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...