During handling of the above exception, another exception occurred

后端 未结 3 1623
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 03:58

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:
        ra         


        
3条回答
  •  野性不改
    2021-02-05 04:18

    Python is alerting you that you threw an exception while another one was in the process of being handled. 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. 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.

    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.

    So to tell Python that you are essentially re-raising the original exception, but with more context, you add 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.

提交回复
热议问题