处理TypeError的Python:

时间:2012-12-11 09:39:19

标签: python exception-handling

我得到了:

TypeError: 'NoneType' object has no attribute '__getitem__' 

错误,因为我的程序正在查询我的数据库。问题是,它会暂停我的整个程序,我不希望在Web应用程序中发生这种情况。

相反,我怎么能优雅地处理它,因为它必须引用一个空字段而我不关心它。这是一段代码片段:

try:
    if not doc['coordinates']:
        xxxxxxxxx
    else:
        xxxxxxxx

except (ValueError, geocoders.google.GQueryError):
    pass

我尝试在TypeError中添加except(),但这会在客户端造成问题。

由于

1 个答案:

答案 0 :(得分:2)

这个怎么样: -

if doc:
    try:
        if not doc['coordinates']:
            xxxxxxxxx
        else:
            xxxxxxxx

    except (ValueError, geocoders.google.GQueryError):
        pass

或者这个: -

    try:
        if not doc or not doc['coordinates']:
            xxxxxxxxx
        else:
            xxxxxxxx

    except (ValueError, geocoders.google.GQueryError):
        pass