Usually, this is a bad practice. But here you go:
try:
<your code here>
except:
pass
This will try your code and if it fails then does nothing.
Example:

In Python, pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results in no operation. The pass statement is useful when you don't write the implementation of a function but you want to implement it in the future.
python - How to properly ignore exceptions - Stack Overflow
python - What is more Pythonic way to handle try-except errors? - Software Engineering Stack Exchange
PEP 760 – No More Bare Excepts - PEPs - Discussions on Python.org
language agnostic - Why use try … finally without a catch clause? - Software Engineering Stack Exchange
Videos
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
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.
It depends on whether you can deal with the exceptions that can be raised at this point or not.
If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.
If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.
However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.
The finally block is used for code that must always run, whether an error condition (exception) occurred or not.
The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.
The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.
Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.