Python Forum
Stack trace shows different exception type than print
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stack trace shows different exception type than print
#1
Python's JSON module supports deserializing Javascript infinities (although the official JSON spec doesn't). Specifically, it supports "Infinity" and "-Infinity" in particular. I need to be able to deserialize "+Infinity" though. Here is my attempt at achieving this
import json

class PositiveInfinityJSONDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.original_scan_once = self.scan_once
        self.scan_once = self._scan_once

    def _scan_once(self, string, idx):
        print("Custom _scan_once entered; trying default first...")
        try:
            return self.original_scan_once(string, idx)
        except json.decoder.JSONDecodeError as e:
            print("Default failed, trying custom logic...")
            try:
                nextchar = string[idx]
            except IndexError:
                raise StopIteration(idx) from e
            if nextchar == '+' and string[idx:idx + 9] == '+Infinity':
                return self.parse_constant('Infinity'), idx + 9
            raise e
        except Exception as e:
            print(f"Got an unexpected exception from default (type: {type(e)}) - {e}")
            raise e

print(json.loads('+Infinity', cls=PositiveInfinityJSONDecoder))
The result of this is that (apparently) a StopIteration exception is thrown, although its traceback looks like a JSONDecodeError
Output:
$ python3 confusion.py Custom _scan_once entered; trying default first... Got an unexpected exception from default (type: <class 'StopIteration'>) - 0 Traceback (most recent call last): File "confusion.py", line 28, in <module> print(json.loads('+Infinity', cls=PositiveInfinityJSONDecoder)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 361, in loads return cls(**kw).decode(s) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I'm baffled because the stack trace clearly shows a JSONDecodeError being raised, but at runtime when I try to catch it, it appears to have a different type. In case the class is doing something funky, I also tried catching a ValueError (its superclass) but that didn't work either.

What does work is catching a StopIteration exception, but that doesn't seem right. I'm afraid that there's something weird going on here and if I catch the wrong exception, there will be some surprise down the line. Does anyone know what's going on here?
Reply


Messages In This Thread
Stack trace shows different exception type than print - by micseydel - Mar-30-2019, 09:28 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  what type of exception to use? Skaperen 3 1,039 Sep-30-2022, 05:00 PM
Last Post: Skaperen
  ModuleNotFound but pip shows module installed biscotty666 2 1,546 Jul-14-2022, 05:17 PM
Last Post: Axel_Erfurt
  Os command output in variable shows wrong value paulo79 2 1,503 Apr-09-2022, 03:48 PM
Last Post: ndc85430
Lightbulb trace library xxxlabradorxxx 1 1,143 Oct-01-2021, 11:30 PM
Last Post: Larz60+
  Help in designing a timestamp finder for chapter-less TV shows Daring_T 1 1,850 Oct-26-2020, 09:30 PM
Last Post: Daring_T
  colorbar for scatter shows no negatives values... gil 0 1,537 Apr-15-2020, 12:45 AM
Last Post: gil
  Exception: Returned Type Mismatch Error devansing 1 5,144 Mar-06-2020, 07:26 PM
Last Post: ndc85430
  Type hinting - return type based on parameter micseydel 2 2,471 Jan-14-2020, 01:20 AM
Last Post: micseydel
  How to fix 'uncaught exception of type NSException' in Python MonsterPython 0 2,150 Jul-09-2019, 06:52 AM
Last Post: MonsterPython
  Tracing a multiplication table w/ Python trace() NationalRex22 0 1,749 Jun-11-2019, 03:31 AM
Last Post: NationalRex22

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020