在一系列语句出错时返回空字符串

0 投票
3 回答
881 浏览
提问于 2025-04-18 03:46

很多时候,我会遇到这样的情况:像下面这样的单独语句可能会抛出一个我并不在乎的异常。如果出现异常,它应该直接返回一个空字符串:

name="".join(b.find(itemprop='name').contents)
phone= "".join(b.find(itemprop='telephone').contents)
fax="".join(b.find(itemprop='faxNumber').contents)

而不是执行所有语句,如果第一个语句出现异常,那么整个执行就会停止,比如:

AttributeError: 'NoneType' object has no attribute 'contents'

所以在这种长长的语句列表中,不想使用try catch finally来处理,我该如何确保强制执行所有语句呢?因为有很多个顺序执行的语句,所以我不想使用try catch这种结构。

3 个回答

2

另一种方法是使用 getattr

name = "".join(getattr(b.find(itemprop="name"), "contents", ""))

在这个例子中,传给 getattrdefault 参数(这里是 "")会在 object(也就是 b.find(...))没有名为 name(即 "contents")的属性时返回。

你还可以通过把这段代码做成一个函数来减少重复:

def find_field(item, prop):
    return "".join(getattr(item.find(itemprop=prop), "contents", ""))


name = find_field(b, 'name')

正如 Jon Clements 指出的,getattr 相比于 try/except 的一个好处是,如果 b.find(...) 抛出一个 AttributeError(也就是说 b 不是你想的那样,可能是个真正的错误),这个错误仍然会被抛出。你可以用以下方式把它改成 try/except

item = b.find(itemprop="name")
try:
    name = "".join(item.contents)
except AttributeError:
    name = ""
2

试着把每个单独的语句抽象成一个函数,然后把 try...catch 放在这个函数里面:

def find_field(name, b):
    try:
        return "".join(b.find(itemprop=name).contents)
    except AttributeError:
        return ""

name = find_field('name', b)
phone = find_field('phone', b)
fax = find_field('fax', b)
2

一种和@jbaiter的解决方案类似的替代方法是使用一个本地函数。这种方法可以避免传递额外的参数,让代码看起来稍微更清晰一些。

你还可以从一开始就避免使用异常:

def find_field(name):
    x= b.find(itemprop=name)
    return "".join(x.contents) if hasattr(x,'contents') else ""

name, phone, fax = map(find_field, ['name','phone','fax'])

撰写回答