How to catch IndentationError Exception in python?

PythonServer Side ProgrammingProgramming

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

Example

try:
def f():
z=['foo','bar']
for i in z:
if i == 'foo':
except IndentationError as e:
print e

Output

"C:/Users/TutorialsPoint1/~.py", line 5
if i == 'foo':
^
IndentationError: expected an indented block


raja
Published on 06-Dec-2017 12:55:44
Advertisements