Converting Exception to a string in Python 3

后端 未结 5 1893
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 23:08

does anyone have an idea, why this Python 3.2 code

try:    
    raise Exception(\'X\')
except Exception as e:
    print(\"Error {0}\".format(str(e)))

5条回答
  •  遥遥无期
    2021-02-04 23:43

    In Python 3.x, str(e) should be able to convert any Exception to a string, even if it contains Unicode characters.

    So unless your exception actually returns an UTF-8 encoded byte array in its custom __str__() method, str(e, 'utf-8') will not work as expected (it would try to interpret a 16bit Unicode character string in RAM as an UTF-8 encoded byte array ...)

    My guess is that your problem isn't str() but the print() (i.e. the step which converts the Python Unicode string into something that gets dumped on your console). See this answer for solutions: Python, Unicode, and the Windows console

提交回复
热议问题