During handling of the above exception, another exception occurred

后端 未结 3 1631
伪装坚强ぢ
伪装坚强ぢ 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:16

    Since you're raising another exception from inside your except statement, python is just telling you that.

    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.

    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.


    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 
        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.


    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.

提交回复
热议问题