Maybe it'd be better to put it into a dedicated function ?
def func(source):
try:
return source.geturl()
except Exception:
try:
return pathlib.Path(os.path.abspath(source.name)).as_uri()
except Exception:
pass
Notes on swallowing exceptions
Ignoring any kind of exception is not the best pattern : it'd be better to know what call can raise what kind of exception.
Even if except ...: pass
is bad, that's already what you were doing in your example, and here it's clear that we try another way if it fails.
The bad programming practice is basing the error handling on the ability to catch any kind of error. In itself, except: pass
is better than except: <lots_of_things_that_wont_raise_again>
.
However, the first answer in the post you referred to says something very sensible : pass
semantically indicates that you won't do ANYTHING with the exception, and as you do not store in a variable, it also shows that you'll never be able to access it again (well you could, but still..). As /u/Aprillion/, you'll want to at least log these errors, because otherwise, you may be swallowing very useful debugging information, which could make your life (or others) much more difficult at some point.
For example, what happens if there's a bug hidden in geturl
, that makes it raises exception in normal cases ? It may stay hidden for long, because this exception will be swallowed and never shown anywhere. Good luck to the debugger to find it !
Ways to improve this
- replace
except Exception
with the exceptions that could be raised
- check before an attempt if it is going to fail, so that you don't have to catch an exception
Additionally, you probably want to use a logger to save/show these exceptions somewhere, at least in DEBUG mode.
Clearly with some spelunking I could figure out which specific errors to catch with a reasonable degree of confidence. But at is explained in this question (Python: How can I know which exceptions might be thrown from a method call) you can't ever be quite certain.
Why would that change anything ? If geturl
returns specific exception types, you'd only catch these, and you'd want other unexpected errors to bubble up to the interpreter.
The big problem with the givn approach is that if geturl
is undefined, or not callable, or take more arguments, this error would not make the interpreter crash, even though it is a clear programming error. That's because except:
or except Exception:
will catch a lof of Python errors, should it be AttributeError
, NameError
, ImportError
or even SyntaxError
.
To conclude, I really think you'd prefer to replace Exception
with the list of exceptions you can catch (and at least send the exceptions to a logger). Note that you can write it as such :
try:
return source.geturl()
except (ExceptionA, ExceptionB, ExceptionC):
pass