64

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.

Ehsan88
  • 3,569
  • 5
  • 29
  • 52
  • 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. Jun 16 '14 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 Jun 16 '14 at 18:01
  • 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 Mar 14 '19 at 16:59

3 Answers3

101
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.

Andy
  • 49,085
  • 60
  • 166
  • 233
21

Use pass:

try:
    foo()
except: 
    pass

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

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
3
try:
  doSomething()
except: 
  pass

or you can use

try:
  doSomething()
except Exception: 
  pass
Dmitry Savy
  • 1,067
  • 8
  • 22