A IndentationError occurs any time the parser finds source code that does not follow indentation rules. We can catch it when importing a module, since the module will be compiled on first import. You can't catch it in the same module that contains the try/except block, because with this exception, Python won't be able to finish compiling the module, and no code in the module will be run.
We rewrite the given code as follows to handle the exception
try: def f(): z=['foo','bar'] for i in z: if i == 'foo': except IndentationError as e: print e
"C:/Users/TutorialsPoint1/~.py", line 5 if i == 'foo': ^ IndentationError: expected an indented block