简体   繁体   English

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

[英]During handling of the above exception, another exception occurred

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 occurred printed out, and how do I resolve it?为什么During handling of the above exception, another exception occurred打印出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)

Currently, you having an issue with raising the ValueError exception inside another caught exception.目前,您在另一个捕获的异常中引发ValueError异常时遇到问题。 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.您应该获得捕获异常的预期结果。

eg例如

>>> 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.更新:看起来有一个PEP 文档解释了如何在异常警告中抑制这些异常。

Since you're raising another exception from inside your except statement, python is just telling you that.由于您从except语句内部引发另一个异常,python 只是告诉您这一点。

In other words, usually you use except to 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/except statement.如果您想“摆脱”该消息,您也许可以在不引发其他异常的情况下向输出写入一些内容,或者仅在不使用try/except语句的情况下使程序第一个停止。


As Steven suggests, 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 much information to it.顺便说一句,做一些像raise Exception('Invalid json: {}'.format(e))并没有多大意义,在这一点上你可以只留下原始异常,因为你没有添加太多信息给它。

Python is alerting you that you threw an exception while another one was in the process of being handled. Python 会提醒您,您抛出了一个异常,而另一个正在处理中。 The warning is there to alert you in case this was unexpected so that you know about the original exception.如果这是意外情况,警告会提醒您,以便您了解原始异常。 Consider a case like the following:考虑如下案例:

class Resource:
  def close(self):
     if cannot_close:
       raise Error("Cannot close")

  def write_data(self, data):
     ...

some_function():
  try:
    res = Resource()
    res.write_data("some data")
  except Error as e:
    res.close()

Let's say that write_data raises an exception, but then the close does so also, unexpectedly.假设write_data引发了一个异常,但是close也出乎意料地这样做了。 When that happens, it's nice to know about both exceptions.发生这种情况时,很高兴了解这两种例外情况。 In most cases, you want to know about the original exception raised by write_data but knowing about the one from close helps you know that something strange happened with close .在大多数情况下,您想了解write_data引发的原始异常,但了解来自close异常有助于您了解close发生了一些奇怪的事情。

But for your case, you are simply restating the original error in a new way.但是对于您的情况,您只是以新的方式重述原始错误。 Doing so lets you provide more context, for example:这样做可以让您提供更多上下文,例如:

with open(json_file) as j:
    try:
        json_config = json.load(j)
    except ValueError as e:
        raise Exception('Invalid json from file {}: {}'.format(json_file, e))

This would provide you with the path of the file that failed to be parsed as JSON, which is helpful context information that won't be in the original exception message.这将为您提供未能解析为 JSON 的文件的路径,这是不会出现在原始异常消息中的有用上下文信息。

So to tell Python that you are essentially re-raising the original exception, but with more context, you add from e .因此,要告诉 Python 您实际上是在重新引发原始异常,但要使用更多上下文,您可以from e添加。

with open(json_file) as j:
    try:
        json_config = json.load(j)
    except ValueError as e:
        raise Exception('Invalid json from file {}: {}'.format(json_file, e)) from e

This is equivalent to "exception chaining" in Java where you supply the original exception to the constructor of the new exception.这相当于 Java 中的“异常链接”,您可以将原始异常提供给新异常的构造函数。

我已经解决了使用data.get(key)而不是data[key]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在处理上述异常期间,发生了另一个异常:Python程序 - During handling of the above exception, another exception occurred: Python program KeyError: 1 在处理上述异常的过程中,又发生了一个异常: - KeyError: 1 During handling of the above exception, another exception occurred: 在处理上述异常的过程中,又发生了一个异常:&amp; google sheet not found - During handling of the above exception, another exception occurred: & google sheets not found “在处理上述异常过程中,发生了另一个异常”for循环中的第一个输入 - “ during the handling of above exception, another exception occurred ” for the first input in the for loop 如何解决“在处理上述异常期间,发生了另一个异常:” - How to fix "During handling of the above exception, another exception occurred: " Flask-restful - 在处理上述异常的过程中,发生了另一个异常 - Flask-restful - During handling of the above exception, another exception occurred 关键错误:1 在处理上述异常的过程中,发生了另一个异常 - Key Error: 1 During handling of the above exception, another exception occurred KeyError:在处理上述异常的过程中,发生了另一个异常 - KeyError: During handling of the above exception, another exception occurred 在处理上述异常的过程中,发生了另一个异常:'Date' - During handling of the above exception, another exception occurred: 'Date' 在处理上述异常期间,发生了另一个异常 - During handling of the above exception, another exception occured
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM