当前接受的答案仅在可调用对象不带任何参数时才有效,要执行一个小片段并抑制它可能引发的某个错误,使用上下文管理器会更容易:
class catch:
def __init__(self,err_type):
valid = True
if isinstance(err_type, tuple):
valid = all(issubclass(e, BaseException) for e in err_type)
else:
valid = issubclass(err_type, BaseException)
if not valid:
raise TypeError("can only catch exception types, not {!r}".format(err_type))
self.catch_err = err_type
def __enter__(self):
return self
def __exit__(self,typ, err, tb):
self.err = err #keep a reference if you want to access later.
if isinstance(err, self.catch_err):
return True
然后你可以像这样运行你的各个部分:
a = b = c = d = "" #default if any fail.
with catch(Exception): #should really specify what kind of exception you are catching!
a = item.something()
with catch(Exception): #should really specify what kind of exception you are catching!
b = item.something2()
b = re.sub(r'\W+', ' ', b)
b = b.strip()
with catch(Exception): #should really specify what kind of exception you are catching!
c = item.something3()
parsed_url = urlparse(b)
if not bool(parsed_url.scheme):
break
with catch(Exception): #should really specify what kind of exception you are catching!
d = item.something4()
当你这样做时,你在没有任何错误检查的情况下a = self.attrs(item.get("data-a"))
调用并将返回值传递给,除非结果是可调用的,否则尝试调用它会引发一个. 您需要传递一个不带参数的可调用对象才能使接受的答案起作用,这只需要您拥有 python 2.7+ 版本来支持该语句。item.get("data-a")
self.attrs
self.attrs
TypeError
with
顺便说一句, if item
is a dict
thendict.get
永远不会引发异常,它在文档中
get(key[, default])
如果键在字典中,则返回键的值,否则返回默认值。如果未给出默认值,则默认为
None
,因此此方法永远不会引发KeyError
。