为什么不能在屏幕上打印两行?
raise KeyError('a\na')
(编辑)
为什么它可以与
ValueError
一起使用?
我需要能够在异常情况下打印出项目符号列表。
最简单的方法是将其转换为字符串并用换行符分割:
try:
raise KeyError('a\na')
except KeyError as e:
strw = str(e)[1:-1].split('\\n')
for s in strw:
print(s)
看起来您必须使用
\\n
作为分隔符,并且引号应该被丢弃。
我也遇到了这个问题并且很好奇。事实证明,原因记录在源代码中:
KeyError
覆盖了__str__
,这样如果它收到空字符串''
,用户将不会收到令人困惑的错误消息。
/*
* KeyError extends LookupError
*/
static PyObject *
KeyError_str(PyBaseExceptionObject *self)
{
/* 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__().
*/
if (PyTuple_GET_SIZE(self->args) == 1) {
return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
}
return BaseException_str(self);
}