在Python 3中捕获KeyError消息

时间:2018-02-18 09:50:36

标签: python string exception-handling

我在Python 3中 $(document).mousemove(function (e) { var target = $(e.target); var msgtext = target.text(); var msg = new SpeechSynthesisUtterance(msgtext); speechSynthesis.speak(msg); }); 中捕获消息时遇到问题(更具体地说是3.5.3)。

输入:

KeyError

输出:

try:
    raise KeyError('some error message')
except KeyError as e:
    if str(e) == 'some error message':
        print('Caught error message')
    else:
        print("Didn't catch error message")

奇怪的是,同样的事情与Didn't catch error message

类似

输入:

IndexError

输出:

try:
    raise IndexError('some index error message')
except IndexError as e:
    if str(e) == 'some index error message':
        print('Caught IndexError message')
    else:
        print("Didn't catch IndexError message")

此外,这个问题似乎特定于Python 3,因为您可以在Python 2中获取Caught IndexError message 属性。

输入:

message

输出:

try:
    raise KeyError('some error message')
except KeyError as e:
    if e.message == 'some error message':
        print 'Caught error message'
    else:
        print "Didn't catch error message"

3 个答案:

答案 0 :(得分:2)

the source code

中完美地解释了这种行为
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__().
    */

答案 1 :(得分:1)

我通过检查错误消息是否在错误字符串中来解决了我的问题:

输入:

Caught error message

输出:

try:
    raise KeyError('some error message')
except KeyError as e:
    if 'some error message' in str(e):
        print('Caught error message')
    else:
        print("Didn't catch error message")

有人可以阐明为什么这有效,但检查平等不是吗?

修改

正如KGSH指出的那样,Caught error message 实际上是str(e)带有单引号。

答案 2 :(得分:1)

@Arda: (因为我无法发表评论)

使用此迷你代码测试后:

<ListView x:Name="TimeLogView">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid>
                                <TextCell Text="{Binding From}" Grid.Column="0" />
                                <TextCell Text="{Binding To}"   Grid.Column="1" />
                                <TextCell Text="{Binding Note}" Grid.Column="2" />
                            </Grid>
                        </ViewCell>
                     </DataTemplate>
                </ListView.ItemTemplate>
 </ListView>

这是输出:

  

抓到了错误消息
  '一些错误信息'
  一些错误信息
  错误

所以区别在于引号。

编辑:我想有人帮助我更好地格式化。