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?

Answer from vartec on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the try statement: The try block will generate an exception, because x is not defined: try: print(x) except: print("An exception occurred") Try it Yourself » · Since the try block raises an error, the except block will be executed. Without the try block, the program will crash and raise an error:
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.5rc1 documentation
The except clause may specify a variable after the exception name. The variable is bound to the exception instance which typically has an args attribute that stores the arguments. For convenience, builtin exception types define __str__() to print all the arguments without explicitly accessing .args. >>> try: ...
Discussions

python - How to properly ignore exceptions - Stack Overflow
When you just want to do a try/except without handling the exception, how do you do it in Python? ... For Python 2 compatible code, pass is the correct way to have a statement that's a no-op. But when you do a bare except:, that's the same as doing except BaseException: which includes GeneratorExit, KeyboardInterrupt, and SystemExit, and in general, you don't want to catch ... More on stackoverflow.com
🌐 stackoverflow.com
Explain Try / Except structure in practical examples?
So think of it this way. Your program is perfect. Prestige. Internally you can totally control interactions, account for mishaps, etc. But! There are outside forces that you can't outright account for, like: An API that is sometimes reachable. And requests crashes An application that you've wrapped in python code A database connection that fails because someone rebooted the server You'll want to be reactive in these cases instead of seeing a traceback. If you expect certain failures and not others you can get more specific and catch certain exceptions. In an imperfect world they're helpful. More on reddit.com
🌐 r/learnpython
21
7
March 23, 2024
Nested try except question
Hi, If my program experiences a problem reading the lines of the file, I would like it to stop and report the error. But I am getting both exception text’s e.g. try: with open('sample.txt', 'r') as reader: fo… More on discuss.python.org
🌐 discuss.python.org
6
0
March 31, 2023
language agnostic - Why use try … finally without a catch clause? - Software Engineering Stack Exchange
When is it appropriate to use try without catch? In Python the following appears legal and can make sense: try: #do work finally: #do something unconditional · However, the code didn't catch anything. Similarly one could think in Java it would be as follows: try { //for example try to get ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 23, 2012
People also ask

What is try/except in Python?
try/except handles exceptions (errors) so your program does not crash unexpectedly.
🌐
pythonbasics.org
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
How do you catch a specific exception?
except ValueError: catches only ValueError exceptions.
🌐
pythonbasics.org
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
What is the finally clause?
Code in finally always runs whether or not an exception occurred.
🌐
pythonbasics.org
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
🌐
Python.org
discuss.python.org › python help
[SOLVED]How to catch error signals without try / except - Python Help - Discussions on Python.org
December 19, 2021 - Hi, First time posting here. I’d like to catch any error signal produced, be it a NameError, IndentationError, or whatnot. I don’t care to escape them, I would just like to be able to call some simple function whenever such an error occurs. Some people might say that this is a bad idea, ...
🌐
Python Basics
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
After the except block, the program continues. Without a try-except block, the last line wouldn't be reached as the program would crash. $ python3 example.py Divided by zero Should reach here · In the above example we catch the specific exception ZeroDivisionError.
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - What you didn’t get to see was the type of error that Python raised as a result of the function call. In order to see exactly what went wrong, you’d need to catch the error that the function raised. The following code is an example where you capture the RuntimeError and output that message to your screen: ... # ... try: linux_interaction() except RuntimeError as error: print(error) print("The linux_interaction() function wasn't executed.")
🌐
Medium
gaitatzis.medium.com › stop-using-try-catch-in-python-2c8f55870372
Stop using Try/Catch in Python. An introduction to Safe Assignment in… | by Adonis Gaitatzis | Medium
December 10, 2024 - We can write a code to execute a function that raises an Error, but reshape the output from a try/ catch to a function that returns a response and Error tuple: def to_safe_assign(function, *args, **kwargs): try: output = function(*args, **kwargs) return output, None except Exception as e: return None, e · Now, to_safe_assign will capture any exception and return it as the error part of a tuple. Simplifies Error Processing: Flattening the if/else stack makes error handling direct and leaves the main logic to run without interruption.
Find elsewhere
Top answer
1 of 12
1242
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
167

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
🌐
GeeksforGeeks
geeksforgeeks.org › python-try-except
Python Try Except - GeeksforGeeks
March 19, 2025 - Example #1: No exception, so the try clause will run. ... # Python code to illustrate # working of try() def divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y print("Yeah !
🌐
Reddit
reddit.com › r/learnpython › explain try / except structure in practical examples?
r/learnpython on Reddit: Explain Try / Except structure in practical examples?
March 23, 2024 -

I am learning python and I've encountered the try / except part of it. I am struggling to understand when I would use this kind of code, probably because I am still very new and most of my code is small programs that have relied on conditional statments.

I guess in my brain I understand the logic of saying "try to do this but if it doesn't work just let it be and keep going with the code". My assumption is this is helpful on larger scale programs in wich you can't afford the time to make sure the code is fail proof and you need the code to buy you time to eventually go back once you have the fail proof option?

Was hoping someone could give me an example of a real life application or website and how this code could apply to it? Because I want to become comfortable with it but unsure how to.

TL,DR: Explain try/except in a practical example so I can understand when and where I would use it?

Thank you!

🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter10.03-Try-Except.html
Try/Except — Python Numerical Methods
Oops! x was not a valid number. Try again... EXAMPLE: If your handler is trying to capture another exception type that the except does not capture it, then we will end up with an error and the execution stops.
🌐
Python.org
discuss.python.org › python help
Nested try except question - Python Help - Discussions on Python.org
March 31, 2023 - Hi, If my program experiences a problem reading the lines of the file, I would like it to stop and report the error. But I am getting both exception text’s e.g. try: with open('sample.txt', 'r') as reader: for line in reader.readlines(): try: print(int(line)) except: print('\nLine error') quit() except: print('\nError: cannot read from the file') where sample.txt contains 1 2 x output current...
🌐
DataCamp
datacamp.com › tutorial › python-try-except
Python Try-Except Tutorial: Best Practices and Real-World Examples | DataCamp
August 26, 2025 - Learn Python try-except with real-world examples, best practices, and common pitfalls. Write cleaner, more reliable error-handling code. ... Get your team access to the full DataCamp for business platform. When Python code runs into problems at runtime, it often raises an exception. Left unhandled, exceptions will crash your program. However, with try-except blocks, you can catch them, recover gracefully, and keep your application running.
🌐
Server Academy
serveracademy.com › blog › python-try-except
Python Try Except - Blog - ServerAcademy.com
When writing Python code, errors can be frustrating. Luckily, Python’s and blocks provide an effective way to manage errors without breaking the flow of your co
Top answer
1 of 9
182

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.

2 of 9
40

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.

🌐
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
January 29, 2026 - I’ve written about this in the blog post ‘How not to handle exceptions in Python‘. Don’t use a blank block when you want to catch a broad range of exceptions. By this, I mean something like: try: ... except: print("An error occurred:")Code language: Python (python) You might encounter this in code samples on the web. If you do, make a habit of improving the exception handling. Why should you, and how can you improve code like the example above?
🌐
Reddit
reddit.com › r/learnpython › best practices for try/except blocks in python script.
r/learnpython on Reddit: Best practices for try/except blocks in Python script.
September 20, 2024 - I am not sure what might be the best practice for using try/except blocks in Python. ... try: some_command_1 except Exception as e: logger.exception(e) try: some_command_2 except Exception as e: logger.exception(e) . . . try: some_command_n except Exception as e: logger.exception(e) ... def main(): command_1() command_2() command_n() if __name__ == "__main__": try: main() except Exception as e: logger.exception(e) When there is an error that raises to a level of an exception, I don't want my script to just catch the exception and move on to the next step.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Try, except, else, finally in Python (Exception handling) | note.nkmk.me
August 15, 2023 - However, it's often preferable not to catch these particular exceptions. In such cases, using Exception instead may be a better option, as described next. You can specify Exception in the except clause, which is the base class for all built-in, non-system-exiting exceptions. Built-in Exceptions - Exception — Python 3.11.3 documentation · def divide_exception(a, b): try: print(a / b) except Exception as e: print(e) divide_exception(1, 0) # division by zero divide_exception('a', 'b') # unsupported operand type(s) for /: 'str' and 'str'
🌐
Programiz
programiz.com › python-programming › exception-handling
Python Exception Handling (With Examples)
The try...except block is used to handle exceptions in Python. Here's the syntax of try...except block: try: # code that may cause exception except: # code to run when exception occurs · Here, we have placed the code that might generate an exception inside the try block. Every try block is followed by an except block. When an exception occurs, it is caught by the except block. The except block cannot be used without the try block.
🌐
Rollbar
rollbar.com › home › when to use try-except vs. try-catch
When to Use Try-Except vs. Try-Catch | Rollbar
July 31, 2023 - The else and finally blocks in both Python and Java are optional. Let’s take a look at several examples. try: print(name) except NameError: print("Variable name is not defined") except: print("Something went wrong")
🌐
Delft Stack
delftstack.com › home › howto › python › try without except in python
How to try Without except in Python | Delft Stack
March 11, 2025 - This tutorial demonstrates how to use the try statement in Python without an except clause. Discover various methods such as context managers, logging, and assertions to effectively monitor exceptions. Learn how to enhance your debugging process while maintaining clean code.