-1

when i run a try except statement to catch a IndentationError ,the statement doesn't work , this is my code:

try: 
    for i in range(2):
    print(i)
except IndentationError:
    print('IndentationError')

then i got the result:

try: 
    for i in range(2):
    print(i)
except IndentationError:
    print('IndentationError')
File "<ipython-input-57-5df0f4cccb57>", line 3
print(i)
    ^
IndentationError: expected an indented block```

why the try except statement doesn't work in this situation ?

lyh
  • 1
  • 2

1 Answers1

1

IndentationError and other SyntaxError exceptions can't be caught in the source file itself, because this is a parsing stage exception. The try is not being run at this point, as the code can't be parsed and compiled into bytecode at this stage.

You can only catch such exceptions in code that triggered the parsing, such as an import statement, or an explicit compile() function call.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343