Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-except clause with an empty except code [duplicate]

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.

like image 500
Ehsan88 Avatar asked Jun 16 '14 17:06

Ehsan88


People also ask

Can I leave except block empty in Python?

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, ...).

Can a try have multiple Except?

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. In this example, we have two except clauses.

What happens if an exception does not have a matching except clause?

If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

Can you have multiple excepts in TRY-except Python?

1. Python Multiple Excepts. It is possible to have multiple except blocks for one try block.


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

like image 182
Andy Avatar answered Sep 20 '22 02:09

Andy