作者:浩劫19_439 | 来源:互联网 | 2022-12-02 17:23
我在下面的try-except中捕获JSON解析错误:
with open(json_file) as j:
try:
json_cOnfig= json.load(j)
except ValueError as e:
raise Exception('Invalid json: {}'.format(e))
为什么要During handling of the above exception, another exception occurred
打印出来,我该如何解决?
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)
Skam..
7
当前,您ValueError
在另一个捕获的异常内引发异常时遇到了问题。这种解决方案的理由对我来说没有多大意义,但是如果您改变
raise Exception('Invalid json: {}'.format(e))
至
raise Exception('Invalid json: {}'.format(e)) from None
编写最终代码。
with open(json_file) as j:
try:
json_cOnfig= json.load(j)
except ValueError as e:
raise Exception('Invalid json: {}'.format(e)) from None
您应该获得捕获异常的预期结果。
例如
>>> foo = {}
>>> try:
... var = foo['bar']
... except KeyError:
... raise KeyError('No key bar in dict foo') from None
...
Traceback (most recent call last):
File "", line 4, in
KeyError: 'No key bar in dict foo'
抱歉,我无法为您解释为什么这特别有效,但似乎可以解决问题。
更新:
好像有一个PEP文档解释了如何在异常警告中抑制这些异常。
1> Skam..:
当前,您ValueError
在另一个捕获的异常内引发异常时遇到了问题。这种解决方案的理由对我来说没有多大意义,但是如果您改变
raise Exception('Invalid json: {}'.format(e))
至
raise Exception('Invalid json: {}'.format(e)) from None
编写最终代码。
with open(json_file) as j:
try:
json_cOnfig= json.load(j)
except ValueError as e:
raise Exception('Invalid json: {}'.format(e)) from None
您应该获得捕获异常的预期结果。
例如
>>> foo = {}
>>> try:
... var = foo['bar']
... except KeyError:
... raise KeyError('No key bar in dict foo') from None
...
Traceback (most recent call last):
File "", line 4, in
KeyError: 'No key bar in dict foo'
抱歉,我无法为您解释为什么这特别有效,但似乎可以解决问题。
更新:
好像有一个PEP文档解释了如何在异常警告中抑制这些异常。