当前位置:  开发笔记 > 编程语言 > 正文

为KeyError打印出奇怪的错误消息

如何解决《为KeyError打印出奇怪的错误消息》经验,为你挑选了1个好方法。

为什么在Python 2.7中

>>> test_string = "a \\test"
>>> raise ValueError("This is an example: %s" % repr(test_string))
ValueError: This is an example: 'this is a \\test'

>>> raise KeyError("This is an example: %s" % repr(test_string))
KeyError: This is an example: 'this is a \\\\test'

(注意4个反斜杠)



1> Martijn Piet..:

__str__对方法ValueErrorKeyError不同:

>>> str(ValueError(repr('\\')))
"'\\\\'"
>>> str(KeyError(repr('\\')))
'"\'\\\\\\\\\'"'

或使用print:

>>> print str(ValueError(repr('\\')))
'\\'
>>> print str(KeyError(repr('\\')))
"'\\\\'"

那是因为KeyError显示了repr()你传入的'key',所以你可以区分字符串和整数键:

>>> print str(KeyError(42))
42
>>> print str(KeyError('42'))
'42'

或者更重要的是,您仍然可以识别空字符串键错误:

>>> print str(KeyError(''))
''

ValueError异常不必处理Python值,它的消息始终是一个字符串.

KeyError_str()CPython源代码中的函数:

/* If args is a tuple of exactly one item, apply repr to args[0].
   This is done so that e.g. the exception raised by {}[''] prints
     KeyError: ''
   rather than the confusing
     KeyError
   alone.  The downside is that if KeyError is raised with an explanatory
   string, that string will be displayed in quotes.  Too bad.
   If args is anything else, use the default BaseException__str__().
*/

ValueError使用默认BaseException_str()函数,对于单参数情况只使用str(arg[0]).

推荐阅读
yzh148448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有