A new way to use `sys.unraisablehook` when try to show the Exception message raise other Exception

Now, the result is:

>>>a = object.__new__(type(exit))
>>>b = {}
>>>b[a]
Traceback (most recent call last):
  File "<python-input-2>", line 1, in <module>
    b[a]
    ~^^^
KeyError: <exception str() failed>

As you see, we don’t know why the message show failed, we can just see the fuzzy message “<exception str() failed>”.
In fact, if the message need to use other object’s __repr__ and the __repr__ raise the Exception, the final message is it. It makes the debug difficult and maybe cause serious problem then.
To solve these problem, I have an ideal:
If the sys.excepthook first try to use str(Exception) then raise, the new Exception will keep to use sys.excepthook, but the count plus 1. If the count above 5, change to use sys.unraisablehook to avoid the infinite loop. In this way we can show more detail while keep safe.

Issue about it:
#135660

Unraisable error is only for errors which cannot be reported as exceptions. For example, if it occurs in the object destructor, in garbage collector, in some callback which is called asynchronously with Python code, or too early in the interpreter initialization stage, or too late in the interpreter shutdown stage, when no Python code is executed, or in during the call of some outdited C API which doe not have way to report an error.

In all other cases, just raise an exception. If an error occured during instantiating an exception, you already have other exception.

3 Likes