Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Syntax Errors be handled?

Tags:

People also ask

Can we handle syntax error in Python?

You can't handle invalid syntax in Python like other exceptions. Even if you tried to wrap a try and except block around code with invalid syntax, you'd still see the interpreter raise a SyntaxError .

What happens when an interpreter finds a syntax error?

A syntax error means the compiler / interpreter is saying "I do not know what you mean by this", so it cannot generate any code or execute any commands until you have fixed it.

What would happen if the syntax in a program is incorrect?

Syntax errors are mistakes in the source code, such as spelling and punctuation errors, incorrect labels, and so on, which cause an error message to be generated by the compiler. These appear in a separate error window, with the error type and line number indicated so that it can be corrected in the edit window.


Consider the following code:

try:
    if True a = 1  #It's missing a colon So it's a SyntaxError!!!!!!!
except SyntaxError:
    print 'hey'

You'd expect it to print hey However It raises a SyntaxError, The same error I'm trying to avoid. So Can all Exceptions be handled using a try-except block? Well If SyntaxError's were an exception why is it included in the built-in exceptions? and finally how can I fix the above piece of code so that it handles the exception properly?

Note: I know what I'm trying to do Is utterly pointless and serves no real purpose