代码之家  ›  专栏  ›  技术社区  ›  rodee

在处理上述异常时,发生了另一个异常

  •  0
  • rodee  · 技术社区  · 6 年前

    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)
    
    2 回复  |  直到 6 年前
        1
  •  47
  •   Skam    6 年前

    目前,您在提出 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 "<stdin>", line 4, in <module>
    KeyError: 'No key bar in dict foo'
    

    抱歉,我不能给你一个解释,为什么这是具体的工作,但它似乎做的把戏。

    看起来有一个 PEP doc 解释如何在异常警告中抑制这些异常。

        2
  •  7
  •   Marco Bonelli    4 年前

    因为你从你的内部提出了另一个例外 except 声明,python只是告诉你。

    换句话说,通常你用 除了 已经在处理一个了 ,这就是python告诉您的。

    try/except 声明。


    Steven

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

    要打印这两个例外,请执行以下操作:

    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)
    

    或者你可以这样做:

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

    抑制第一个,只记录 Invalid json... 例外。


    顺便说一下 raise Exception('Invalid json: {}'.format(e)) 实际上没有什么意义,在这一点上,您可以只保留原始异常,因为您没有向它添加太多信息。

        3
  •  1
  •   GreenGiant WoodenKitty    4 年前

    Python警告您在处理另一个异常时抛出了一个异常。该警告用于在发生意外情况时向您发出警告,以便您了解原始异常。考虑以下情况:

    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()
    

    write_data close 出乎意料的是,他也这么做了。当这种情况发生时,很高兴知道这两个例外。在大多数情况下,您希望了解 写入\u数据 有助于你知道发生了什么奇怪的事情 关闭

    但对于您的情况,您只是以一种新的方式重新声明原始错误。这样做可以提供更多的上下文,例如:

    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 .

    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
    

    这相当于Java中的“异常链”,在Java中,您将原始异常提供给新异常的构造函数。