🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
You can use the else keyword to define a block of code to be executed if no errors were raised: In this example, the try block does not generate any error: try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") ...
🌐
Reddit
reddit.com › r/learnpython › is it ok to catch an exception and do nothing, if the exception is expected?
r/learnpython on Reddit: Is it OK to catch an exception and do nothing, if the exception is expected?
May 29, 2019 -

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

🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block. If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with an error message.
🌐
Quora
quora.com › How-do-you-ignore-an-exception-and-proceed-in-python
How do you ignore an exception and proceed in python?
Answer (1 of 2): First off, let’s be clear that ignoring exceptions is often not the right thing to do. The classical way to do it is to just accept the exception and pass: [code]>>> def remover(filename): ... import os ... try: ... os.remove(filename) ... except FileNotFoun...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-try-without-except
Using try without except (ignoring exceptions) in Python | bobbyhadz
Copied!my_list = [] # ✅ Ignore ... # 👇️ this runs pass ... The pass statement does nothing and is used when a statement is required syntactically but the program requires no action....
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-try-except
Python Try Except - GeeksforGeeks
July 23, 2025 - If any exception occurs, but the except clause within the code doesn't handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
🌐
PythonHello
pythonhello.com › problems › exceptions › how-to-properly-ignore-exceptions
How to properly Ignore Exceptions in Python
try: # some code that might raise an exception x = 1 / 0 except ZeroDivisionError: # this block of code will be executed if a ZeroDivisionError is raised # we can ignore the exception by doing nothing here pass
🌐
Python.org
discuss.python.org › python help
Type, except, not working - Python Help - Discussions on Python.org
June 5, 2021 - why my excepts are not executing? def TestNumbers(x,y,z): try: X = int(x) y = int(y) z = int(z) print(‘You have provided valid values’) except NameError: print('NameError') except: print("You have provided invalid inputs to the function") if x == y and x == z: return True else: return False print(TestNumbers(5,6,8)) print() print(TestNumbers(“a”,5,8)) print(TestNumbers(a,6,7))
Find elsewhere
Top answer
1 of 3
5

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.

2 of 3
4

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.

🌐
Python Land
python.land › home › language deep dives › python try except: examples and best practices
Python Try Except: Examples And Best Practices • Python Land Tutorial
December 29, 2021 - If you call a Python function inside the try block, and an exception occurs in that function, the flow of code execution stops at the point of the exception and the code in the except block is executed. Try doing this again without try and except. You’ll see that Python prints the exception for us.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-ignore-an-exception-and-proceed-in-python
How to Ignore an Exception and Proceed in Python - GeeksforGeeks
July 23, 2025 - The suppress function is used to specify the ZeroDivisionError exception to be suppressed. If the code inside the with block raises a ZeroDivisionError, it will be suppressed and execution will continue after the with block.
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter10.03-Try-Except.html
Try/Except — Python Numerical Methods
If the exception does not match the ExceptionName, it is passed on to outer try statements. If no other handler is found, then the execution stops with an error message. EXAMPLE: Capture the exception. x = '6' try: if x > 3: print('X is larger than 3') except TypeError: print("Oops! x was not a valid number. Try again...") Oops! x was not a valid number. Try again...
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - Python even groups some of the ... that Python raises depending on system error codes. If you still didn’t find a fitting exception, then you can create a custom exception. You can give the function a try by adding the following code: ... The way you handled the error here is by handing out a pass. If you run this code on a macOS or Windows machine, then you get the following output: ... You got nothing in ...
🌐
Towards Data Science
towardsdatascience.com › home › latest › quick python tip: suppress known exception without try except
Quick Python Tip: Suppress Known Exception Without Try Except | Towards Data Science
January 21, 2025 - It is very common to use thetry ... except ... block to handle exceptions in Python. It enabled us to apply some special operations when there is something goes wrong. ... If the situation satisfies the above conditions, you don’t have to use try ... except ... to handle the exceptions.
Top answer
1 of 12
1240
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:

  • try statement
  • exceptions

However, it is generally bad practice to catch every error - see Why is "except: pass" a bad programming practice?

2 of 12
166

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
🌐
freeCodeCamp
freecodecamp.org › news › python-try-and-except-statements-how-to-handle-exceptions-in-python
Python Try and Except Statements – How to Handle Exceptions in Python
September 23, 2021 - Let's start by understanding the syntax of the try and except statements in Python. The general template is shown below: try: # There can be errors in this block except <error type>: # Do this to handle exception; # executed if the try block throws an error else: # Do this if try block executes successfully without errors finally: # This block is always executed
🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.3 documentation
In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement with an except clause that mentions a particular class, that clause also handles any excep...
🌐
Devcuriosity
devcuriosity.com › manual › details › python-try-except-finally-continue-break-loops
Python - Try, Except, Finally, Continue, Break in Loop Control Flow with examples
finally - Executes at the end of ... that it will still execute if break or continue was called within the try/except block. pass - Simply does nothing and serves as a placeholder....