pythonsyntaxtry-catchindentation

How can I write an empty indented block (and avoid an IndentationError) in Python?


I have some code like:

try:
    do_the_first_part()
except SomeError:
do_the_next_part()

I get an error that says "expected an indented block" - but I don't want to write anything inside my except block, I just want it to catch and swallow the exception. How can I do this in Python?


See also: How to use "pass" statement?


Solution

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