The current accepted answer would only work if the callable did not take any arguments, to execute a small snippet and suppress a certain error it might raise it would be easier to use a context manager:
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
Then you can run your individual parts like this:
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()
When you do a = self.attrs(item.get("data-a"))
you are calling item.get("data-a")
without any error checking and passing the return value into self.attrs
, unless the result is callable trying to call it in self.attrs
will raise a TypeError
. You would need to pass a callable that takes no arguments for the accepted answer to work, this only requires you have python version 2.7+ for support for the with
statement.
By the way, if item
is a dict
then dict.get
will never raise an exception, it is in the documentation
get(key[, default])
Return the value for key if key is in the
dictionary, else default. If default is not given, it defaults to
None
, so that this method never raises a KeyError
.