How to write an empty indentation block in Python?

好久不见. 提交于 2019-11-27 03:01:53

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1528903/how-to-write-an-empty-indentation-block-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!