Catch SyntaxError Exception in Python



A SyntaxError occurs any time the parser finds a source code it does not understand. This can be while importing a module, invoking exec, or calling eval(). Attributes of the exception can be used to find exactly what part of the input text caused the exception.

Catch SyntaxError Exception

To find out what part of the code leads to a syntax error, we need to use certain attributes of exception in order to check which part of the text given as input leads to the exception.

Example

In the below example code eval() will raise a SyntaxError because the "Let's learn Python" is not valid Python syntax.

try:
    eval('Lets learn Python')  
except SyntaxError as err:  
    print('Syntax error in file {} on line {} at column {}: {}'.format(
        err.filename, err.lineno, err.offset, err.text.strip()))
    print(err)

Output

Syntax error in file <string> on line 1 at column 6: Lets learn Python
invalid syntax (<string>, line 1)

SyntaxError During Importing a Module

While attempting to import a module with an invalid name then SyntaxError is raised and details are printed.

Example

In the example, code invalid_module_name would raise an ImportError instead of SyntaxError while attempting to import a module with an invalid name.

try:
    import invalid_module_name 
except ImportError as err:
    print(f"Import error: {err}")

Output

Import error: No module named 'invalid_module_name'

Using 'exec()' to Execute Incorrect Code

The exec() function can dynamically execute the code of Python programs. The code can be passed in as a string or object code to this function.

Example

In the below example code exec() function tries to execute the string, but a missing colon causes a SyntaxError.

try:
    exec("if True print('Hello')") 
except SyntaxError as err:
    print(f"Syntax error in file {err.filename} on line {err.lineno} at column {err.offset}: {err.text.strip()}")

Output

Syntax error  (1-7): if True print('Hello')
Updated on: 2024-10-09T13:57:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements