-3

The following is Python code that I typed:

import builtins
try:
    a = input("Enter name :- ")
    if (a=='Joey'):
        print("Yeah right ?!?")
          print("How come")
    else:
        print("No Problem")
except IndentationError as i:
    print("Error : {0}".format(i))

Instead of handling the exception and printing the error message, I get an "Unexpected indent" error message.

Why is this happening?

Thanks in advance.

neminem
  • 2,658
  • 5
  • 27
  • 36

3 Answers3

2

You cannot catch syntax errors (including indentation errors) in the code that triggers the exception itself.

The exception is thrown by the parser as it loads your file, not as it runs the code. The code is never run because of the error.

You can only catch the exception from the 'outside', when loading the module with import or when passing text to the compile() function, for example.

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

You cannot catch errors caught by the actual compiler.

A SyntaxError or an IndentationError would mess up your actual code, not what your code is supposed to do, resulting in an immediate error.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
0

Python is failing because the interpreter sees the syntax error and stops; your code never gets a chance to execute. It will only throw an IndentationError on code which it sees after the program has been compiled:

has_syntax_error = '''
    print ("something")
      print ("somethign else")
'''

try:
    eval (has_syntax_error)
except IndentationError:
    print ("Caught exception")
Guy
  • 167
  • 9