Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch IndentationError Exception in python?

The following code throws an error

def f():
    z=['foo','bar']
    for i in z:
    if i=='foo':
    …….

How to handle this exception and know its type?


1 Answer
Manogna

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

OUTPUT

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.