Try-except clause with empty except code

Sometimes you don’t want to put any code in the except part, because you just want to be sure that the code works without errors, but you are not interested in catching them. I could do it like this in C #:

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

How can I do this in Python ?, because indentation does not allow this:

 try: do_something() except: i_must_enter_somecode_here() 

By the way, it is possible that what I am doing in C # also does not comply with the principles of error handling. I appreciate it if you have thoughts about it.

+7
python try-except
source share
3 answers
 try: do_something() except: pass 

You will use the pass statement.

The skip instruction does nothing. It can be used when the instruction is required syntactically, but the program does not require any action.

+10
source share

Use pass :

 try: foo() except: pass 

A pass just a placeholder for nothing, it just passes to prevent SyntaxError s.

From the docs :

The skip instruction does nothing. It can be used when the operator is required syntactically, but the program does not require action.

As you can see, we want to create an empty function that raises a SyntaxError without a body:

 >>> def foo(): ... File "<stdin>", line 2 ^ IndentationError: expected an indented block >>> 

However, pass replaces this void:

 >>> def foo(): ... pass ... >>> foo() >>> 
+3
source share
 try: doSomething() except: pass 

or you can use

 try: doSomething() except Exception: pass 
+1
source share

All Articles