Try-except clause with an empty except code

PythonTry Except

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Use pass:

try:
    foo()
except: 
    pass

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

Solution 3 - Python

try:
  doSomething()
except: 
  pass

or you can use

try:
  doSomething()
except Exception: 
  pass

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEhsan88View Question on Stackoverflow
Solution 1 - PythonAndyView Answer on Stackoverflow
Solution 2 - PythonA.J. UppalView Answer on Stackoverflow
Solution 3 - PythonDmitry SavyView Answer on Stackoverflow