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
These exceptions can be handled ... 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.4 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

Is it okay to use try/finally without except?
Code after finally will be called whether the code after the try works or not. It doesn't care. Gets called every time. If you need something to run IF AND ONLY IF the code in the try FAILS, then you need to use except. More on reddit.com
🌐 r/learnpython
6
11
February 12, 2016
[SOLVED]How to catch error signals without try / except
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, ... More on discuss.python.org
🌐 discuss.python.org
6
0
December 19, 2021
language agnostic - Why use try … finally without a catch clause? - Software Engineering Stack Exchange
The classical way to program is with try ... catch. When is it appropriate to use try without catch? In Python the following appears legal and can make sense: try: #do work finally: #do some... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 23, 2012
Is using try/except bad? How to avoid/substitute it.
try/except is usually used for non-deterministic things. Is the user input OK as floating point? Can you read that file OK? If it's things that are easily deterministic, like reaching the end of a list, then the code would probably cleaner using a different structure. More on reddit.com
🌐 r/learnpython
87
17
February 23, 2024
Top answer
1 of 12
1241
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
🌐
Reddit
reddit.com › r/learnpython › is it okay to use try/finally without except?
r/learnpython on Reddit: Is it okay to use try/finally without except?
February 12, 2016 -

Hi and sorry for the noob question,

I am calling another python script as a subprocess. The python script tries to do X, and if/when it fails it MUST do Y. I had originally been handling this by doing the following:

 try:
    x
except:
   <code to be run>

For what I want to do, would it be better to simply use:

try:
    x
finally:
    y

If I understand correctly, I am basically using except for something finally should be used for at the moment, yes? Is there any downside to not using except for what I want to accomplish?

Top answer
1 of 4
8
Code after finally will be called whether the code after the try works or not. It doesn't care. Gets called every time. If you need something to run IF AND ONLY IF the code in the try FAILS, then you need to use except.
2 of 4
1
try will attempt a piece of code. If that results in exception, you can capture and handle that exception within except. Whether or not an exception occurred, you can run code in a finally block to guarantee that it runs in all circumstances. That way, even if the exception stops the program, code in the finally block will still execute. For your purpose, you may want to have all three in place: try: # try this code which may cause an Exception except AThingHappened as e: # handle the exception finally: # code that occurs whether exception happened or not. When you run code in the except block, it's possible to prevent that exception from stopping your program. This is a good way to handle common errors, such as the one you're expecting when you run your subscript. If you want, you can choose to raise the exception again from inside the except block, which lets it bubble up through the program until something else catches it or the thread ceases execution. In either case, any code in finally will be run. This is useful for some code that might do some clean up, like closing a connection. To more directly answer your question, if you omit the except block, your code in finally will still run, but you won't be handling the exception. Instead, that exception will be raised and you'll see its traceback in the console. If you have some logic you want to use to handle that exception, use an except statement. However, depending on your use-case, you might do better designing something that can work with the with statement . I don't know the specifics of your program, so I can't say if it would be helpful, but it's worth considering before trying to make something that's overly complex using try..except..finally.
🌐
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, ...
🌐
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.
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.

Find elsewhere
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - It’s bad practice to catch all exceptions at once using except Exception or the bare except clause. Combining try, except, and pass allows your program to continue silently without handling the exception.
🌐
GeeksforGeeks
geeksforgeeks.org › python-try-except
Python Try Except - GeeksforGeeks
March 19, 2025 - # 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 ! Your answer is :", result) except ZeroDivisionError: print("Sorry ! You are dividing by zero ") # Look at parameters and note the working of Program divide(3, 0) ... Example #3: The other way of writing except statement, is shown below and in this way, it only accepts exceptions that you're meant to catch or you can check which error is occurring.
🌐
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.
🌐
Python Basics
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
The try except statement can handle exceptions. Exceptions may happen when you run a program. Exceptions are errors that happen during execution of the program. Python won't tell you about errors like syntax errors (grammar faults), instead it will abruptly stop.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-try-without-except
Using try without except (ignoring exceptions) in Python | bobbyhadz
Copied!my_list = [] # ✅ Ignore any exception try: # 👇️ raises ValueError my_list.remove(1000) except: # 👇️ this runs pass ... The pass statement does nothing and is used when a statement is required syntactically but the program requires no action. In general, using an except statement without explicitly specifying the exception type is considered a bad practice. This is mostly because catching any error makes your code less intuitive and more difficult to read.
🌐
GeeksforGeeks
geeksforgeeks.org › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
In case an error occurs in try-block, ... try block and jumps to exception block. These blocks let you handle the errors without crashing ... In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error.We can catch exceptions ...
Published   September 8, 2024
🌐
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'
🌐
Reddit
reddit.com › r/learnpython › is using try/except bad? how to avoid/substitute it.
r/learnpython on Reddit: Is using try/except bad? How to avoid/substitute it.
February 23, 2024 -

Basically I've heard that using try and except is bad as it cultivates bad habits. But I'm not sure how to avoid using these when searching through lists using a "for" loop as it'll give index error otherwise. Basically it tries to check a list (which is the board) whether it has 3 in a row like in tic tac toe, but the board isnt a standard 3x3 and can be whatever and it still successfully detects a 3 in a row.

My code works fine but it includes like 4 separate try and excepts in a for loop which is in another for loop and I'm not sure if thats good

Btw i also dont use except only, I use except IndexError.

🌐
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 - Note that the number zero has no reciprocal. So, if we write code as follows without handling exceptions, a ZeroDivisionError will be thrown. ... The most common and intuitive way of solving this problem is to have a try ... except ... block to catch the ZeroDivisionError exception and ignore it.
Top answer
1 of 5
7

If try is technically just a scope marker, it is functionally redundant when scopes are already clear. It is no problem to define a language in which try can be "folded" directly into a preceding scope marker.

For example, it is trivial to treat

while ...
  ...
catch e
  ...

as syntactic sugar for

while ...
  try
    ...
  catch e
    ...

which is similar to Ruby's semantics.

Relatedly, if your language is expression based you can have an <expr> catch <name> <expr(name)> construct/operator/... that trivially expands to a longer form. For example, this even was proposed for Python and only rejected for non-technical reasons.


What you should ask yourself is if exception handling for an entire, given scope is actually a good thing. Consider that your tiny example is intended to catch an error from factorial, but actually it would handle two to three things.

To clarify, let me write that part the way I would do for my dayjob:

try:
   result = factorial(i)
except e:
   print('Factorial of', i, 'resulted in', e.message)
   break
else:
   print('Factorial of', i, 'is', result)
   i += 1

Notice how the factorial handler really only deals with the factorial execution! It does not handle whether formatting strings works, whether printing works, or even whether incrementing works. These are all actions where an error is not expected by your handler, so if one does occur it should absolutely be loud and definitely not accidentally silenced.
Precisely handling errors is something you absolutely do want to offer. And probably (since correct error handling is your goal) you don't just want to offer it, but also encourage it - or even discourage imprecise error handling!

By inviting people to be sloppy and re-use logical scopes as error scopes, you make error handling worse. So at the very least, you should offer something to add explicit scopes. This can be a generic scope mechanism, and in your example syntax it would map to a separate keyword:

while ...
  .
  .
  scope
    .
  catch e
    ...

But at this point you are almost all the way to having try, especially if the scope has little or no other use. So basically you have to ask yourself whether you are willing to pay the price of having a try keyword or not - because most if not all of the other cost you should be prepared to pay anyway.

2 of 5
5

The lack of an explicit try makes it harder to catch exceptions from only some places.

Put together with your other proposal to make exceptions homogeneous, it will be harder in multiple ways for programmers to catch and handle some exceptional cases while allowing others to propagate. It will also be more likely that programmers will mistakenly catch (and accidentally suppress) exceptions they did not intend to.


Consider code like this:

file = acquire_foo()

try:
    foo.bar()
    foo.baz()
catch:
    print('failed to bar and baz the foo')

This shape of code is very common, where we want to acquire a resource and do something with it, and handle the error if the latter fails. Note that the try: specifically occurs after acquire_foo(), meaning if we fail to acquire the resource, the exception will not be caught. This is the programmer's intention, but expressing that intention requires an explicit try. There is no easy way to write this code otherwise.

You could get around this by making catch only apply to the preceding statement, and allowing grouping using optional braces:

foo = acquire_foo()

{ // these together are one statement
    foo.bar()
    foo.baz()
}
catch:
    // this only catches exceptions from the previous block statement
    ...

However, besides having the same indentation you were trying to avoid by omitting try, this is an accident waiting to happen. People will forget to do this. It's particularly a problem when acquire_foo() and foo.bar() can signal the same type of exception (e.g. a database error), because if you catch from both by accident, you'll mishandle acquire_foo()'s error as if it was thrown by foo.bar().

🌐
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 - You have to flag for the stacktrace, and the Python exc_info explanations, e.g. “list index out of range” (you could probably just use logger.exception(e) as well) Just read the documentation, you most likely won’t really need much more complicated stuff here. Generally speaking the best practice is to already know which errors can be thrown, look above, I’m catching individual errors and handling them differently, do that! and try not use the generic ‘Exception’, .
🌐
Codingem
codingem.com › home › ‘try…catch’ in python: it’s called ‘try…except’ (error handling guide)
'try...catch' in Python: It's Called 'try...except' (Error Handling Guide)
November 27, 2022 - To fix the earlier example, you need to know that when you’re accessing an undefined variable in Python, you should expect it to cause a NameError. Now you can expect a potential NameError in the except block: try: print(x) except NameError: print("NameError: x is not defined.") ... NameError: x is not defined. This not only makes the code more readable but also ensures you know what you’re doing. It’s much better to specify the type (or types) of error you might face instead of just catching a generic error.
🌐
Programiz
programiz.com › python-programming › exception-handling
Python Exception Handling (With Examples)
Here's the syntax of try...except ... 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....