Python 在处理上述异常的过程中,又发生了一个异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52725278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:10:10  来源:igfitidea点击:

During handling of the above exception, another exception occurred

pythonpython-3.x

提问by rodee

I have below try-except to catch JSON parse errors:

我有以下 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))

Why is During handling of the above exception, another exception occurredprinted out, and how do I resolve it?

为什么会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)

回答by Skam

Currently, you having an issue with raising the ValueErrorexception inside another caught exception. The reasoning for this solution doesn't make much sense to me but if you change

目前,您ValueError在另一个捕获的异常中引发异常时遇到问题。这个解决方案的推理对我来说没有多大意义但如果你改变

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 docexplaining how to suppress these exception inside exception warnings.

更新:看起来有一个PEP 文档解释了如何在异常警告中抑制这些异常。

回答by Marco Bonelli

Since you're raising another exception into your exceptstatement, python is just telling you that.

由于您在except语句中提出了另一个异常,python 只是告诉您这一点。

In other words, usually you use exceptto handle an exception and not make the program fail, but in this case you're raising another exception while already handling one, which is what python is telling you.

换句话说,通常你except用来处理异常而不是使程序失败,但在这种情况下,你在处理一个异常的同时引发另一个异常,这就是 python 告诉你的。

There is really nothing to be worried about, if that's the behavior you want. If you want to "get rid" of that message, you can perhaps write something to the output without raising another exception, or just make the first halt the program without using a try/exceptstatement.

如果这是您想要的行为,那真的没有什么可担心的。如果您想“摆脱”该消息,您也许可以在不引发其他异常的情况下向输出写入一些内容,或者只是在不使用try/except语句的情况下使程序停止。



As Stevensuggests, you can do:

正如史蒂文所建议的,你可以这样做:

raise Exception('Invalid json: {}'.format(e)) from e

to get both exceptions printed, like this:

打印两个异常,如下所示:

Traceback (most recent call last):
  File "tmp.py", line 5, in <module>
    raise Exception('Invalid json: {}'.format(e)) from e
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  <...>
    json.decoder.JSONDecodeError: Expecting ',' delimiter: line 103 column 9 (char 1093)

Or you can do this:

或者你可以这样做:

raise Exception('Invalid json: {}'.format(e)) from None

To suppress the first one and only log the Invalid json...exception.

抑制第一个并且只记录Invalid json...异常。



By the way, doing something like raise Exception('Invalid json: {}'.format(e))doesn't really make much sense, at that point you can just leave the original exception alone, since you're not adding very much information to it.

顺便说一句,做类似的事情raise Exception('Invalid json: {}'.format(e))并没有多大意义,在这一点上你可以只留下原始异常,因为你没有向它添加太多信息。