Try-except clause with an empty except code

Question:

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.

Asked By: Ehsan88

||

Answers:

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.

Answered By: Andy
try:
  doSomething()
except: 
  pass

or you can use

try:
  doSomething()
except Exception: 
  pass
Answered By: Dmitry Savy

Use pass:

try:
    foo()
except: 
    pass

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

Answered By: A.J. Uppal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.