During handling of the above exception, another exception occurred

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

    Currently, you having an issue with raising the ValueError exception inside another caught exception. 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.

    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 "", line 4, in 
    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.

提交回复
热议问题