views:

303

answers:

2

The runtime keeps telling me:

expected an indented block

But I don't want write nothing inside my except block, I just want it to catch and swallow the exception.

+15  A: 

Just write

pass

as in

try:
    # Do something illegal.
    ...
except:
    # Pretend nothing happened.
    pass

EDIT: @swillden brings up a good point, viz., this is a terrible idea in general. You should, at the least, say

except TypeError, DivideByZeroError:

or whatever kinds of errors you want to handle. Otherwise you can mask bigger problems.

Peter
Be careful with using that idiom as expressed above. A generic "except" will catch any exception, including many programming errors like referencing undefined variables, etc, and the empty clause will just swallow the exceptions. You can hide serious problems this way.
swillden
A better example idiom might be "while condition-with-side-effects : pass". That said, conditions with side-effects can have an odour too.
Steve314
Exceptions are very expensive. Use them wisely.
Austin
Austin: Wher do you have that wisdom from? Updated it with Python? Python Exceptions aren't terribly expensive, and you should use them when appropriate.
kaizer.se
A: 

I've never done this in more permanent code, but I frequently do it as a placeholder

if some_expression:
  True
else:
  do_something(blah)

Just sticking a True in there will stop the error. Not sure if there's anything bad about this.

Josh
There's nothing wrong with that technically, but these situations is why 'pass' exists in the first place.
efotinis
it is bad only since it throws readers off, it's absolutely not idiomatic.
kaizer.se