69

Sometimes you don't want to place any code in the except part because you just want to be assured of a code running without any error but not interested to catch them. I could do this like so in C#:

try
{
 do_something()
}catch (...) {}

How could I do this in Python ?, because the indentation doesn't allow this:

try:
    do_something()
except:
    i_must_enter_somecode_here()

BTW, maybe what I'm doing in C# is not in accordance with error handling principles too. I appreciate it if you have thoughts about that.

4
  • 3
    Generally to the empty catch block: I had to work with and debug an application lately which was written by somebody who seemed to love empty catch blocks. I don't know why you would do this but finding an error in such an application is horrible. You see from the results that something went wrong but to tackle it you have to work a lot with MsgBox and stuff.
    – Martin K.
    Commented Jun 16, 2014 at 17:48
  • 3
    Ignoring a specific exception by using pass in the except block is totally fine in Python. Using bare excepts (without specifying an exception type) however is not. Don't do it, unless it's for debugging or if you actually handle those exceptions in some way (logging, filtering and re-raising some of them, ...).
    – Lukas Graf
    Commented Jun 16, 2014 at 18:01
  • 1
    People still upvote this question sometimes, but as the OP, now that I am more involved in the programming business have an advice and that is, always have a habit that you at least log things in your code. So an empty except block is not a good thing. Don't learn it. Just think about what kind of log code you can include in there. In the long run that habit would save you much more time.
    – Ehsan88
    Commented Mar 14, 2019 at 16:59
  • From the maintenance perspective, yeah, it's bad... using a "pass" is the way to go and ALSO, place a comment why you did that and save future headache... most likely for others :-)
    – AlexD
    Commented Oct 24, 2023 at 18:46

3 Answers 3

107
try:
    do_something()
except:
    pass

You will use the pass statement.

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

22

Use pass:

try:
    foo()
except: 
    pass

A pass is just a placeholder for nothing, it just passes along to prevent SyntaxErrors.

3
try:
  doSomething()
except: 
  pass

or you can use

try:
  doSomething()
except Exception: 
  pass

Not the answer you're looking for? Browse other questions tagged or ask your own question.