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.
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, ...).
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.
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.
1. Python Multiple Excepts. It is possible to have multiple except blocks for one try block.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With