except Exception:
pass
Python docs for the pass statement
Answer from Andy Hume on Stack Overflowexcept Exception:
pass
Python docs for the pass statement
Generic answer
The standard "nop" in Python is the pass statement:
try:
do_something()
except Exception:
pass
Using except Exception instead of a bare except avoid catching exceptions like SystemExit, KeyboardInterrupt etc.
Python 2
Because of the last thrown exception being remembered in Python 2, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of pass:
try:
do_something()
except Exception:
sys.exc_clear()
This clears the last thrown exception.
Python 3
In Python 3, the variable that holds the exception instance gets deleted on exiting the except block. Even if the variable held a value previously, after entering and exiting the except block it becomes undefined again.
I'm struggling to word this properly but here goes anyway.
If we know a specific exception will be thrown under certain circumstances, is it OK to catch that exception and not tell the user or log it anywhere? Or should an exception always be logged somewhere?
For example, let's say KeyError is expected under certain circumstances, e.g. if a dictionary that is created programmatically doesn't contain an item, yet. In one of my apps, I have that exact situation because the item that will eventually reside there hasn't been extracted from my XML file, yet. Until that time, I'm catching the KeyError, and carrying on knowing the KeyError eventually won't be thrown when I finish processing the XML. Terrible explanation, but I hope it makes sense.
Is that OK or would it be better practice to initialise the dictionary first, say in the class __init__ method so that the KeyError never happens, ever?
Thanks
Neither of these is more Pythonic than the other. The examples are too trivial to say which is preferrable but it really all depends on how things should work.
Catch and logging/reporting an issue is just a hair's breadth away from squashing exceptions which is almost always a terrible idea. The only reason I can see doing this is that you want whatever the issue is to not stop execution. If you are going to do something like this, it's really crucial to make sure that you return something sensible that works for the caller. If the next thing that happens is that the calling code throws its own exception because e.g., None doesn't have an add method, you are at best just making things harder to troubleshoot. It could be a lot worse, however. A lot of serious bugs are due to returning nulls/None after catching an error. I think there are times that is makes sense to do this, but they are rare in my experience.
Allowing the raw exception to bubble out is the next least-worst option, IMO. This can be fine if you are building something small where it will be easy to find the what the problem is when things crash with a KeyError. In a situation where you are leveraging a lot of duck-typing, passing around function references, or using annotations, it can sometimes be difficult. For example, if you are using this code behind a web endpoint, what HTTP error code should you use when you catch a KeyError. 500 might be the right answer in most cases but there might be times you want to produce something else depending on where the key was not found.
That brings me to the last option which you don't mention: catch and raise a separate, more meaningful error. That allows you to distinguish between say, a KeyError thrown because the request was for something that isn't valid and a KeyError thrown because of a bad configuration.
Neither is pythonic. Pythonic code would be:
my_dict = {}
def fetch_value(key):
return my_dict[key]
val = fetch_value('my_key')
Remember, simple is better than complex and flat is better than nested. Since your except-block does not handle the exception in any meaningful way, it is better to just let it bubble up the call stack and terminate the program.
But in your code the error is ignored and it implicitly returns None if the key is not found. If this is what you want, then it can be done simpler with the get() method:
def fetch_value(key):
return my_dict.get(key)
"Handling" an error by just logging a message and then continuing as if nothing happened, is a terrible antipattern from the Java world which has no place in Python. Exceptions should only be caught if they can be meaningfully handled.
try:
doSomething()
except Exception:
pass
or
try:
doSomething()
except:
pass
The difference is that the second one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from BaseException, not Exception.
See documentation for details:
trystatement- exceptions
However, it is generally bad practice to catch every error - see Why is "except: pass" a bad programming practice?
It's generally considered best-practice to only catch the errors you are interested in. In the case of shutil.rmtree it's probably OSError:
>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
[...]
OSError: [Errno 2] No such file or directory: '/fake/dir'
If you want to silently ignore that error, you would do:
try:
shutil.rmtree(path)
except OSError:
pass
Why? Say you (somehow) accidently pass the function an integer instead of a string, like:
shutil.rmtree(2)
It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug.
If you definitely want to ignore all errors, catch Exception rather than a bare except: statement. Again, why?
Not specifying an exception catches every exception, including the SystemExit exception which for example sys.exit() uses:
>>> try:
... sys.exit(1)
... except:
... pass
...
>>>
Compare this to the following, which correctly exits:
>>> try:
... sys.exit(1)
... except Exception:
... pass
...
shell:~$
If you want to write ever better behaving code, the OSError exception can represent various errors, but in the example above we only want to ignore Errno 2, so we could be even more specific:
import errno
try:
shutil.rmtree(path)
except OSError as e:
if e.errno != errno.ENOENT:
# ignore "No such file or directory", but re-raise other errors
raise
So basically I have:
try:
list.remove(foo)
except ValueError:However, Python doesn't let me leave the except blank. How do I write the try-except so that if I get a ValueError, I just ignore it?
Sorry for the beginner question!