
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Catch SyntaxError Exception in Python
SyntaxError in Python occurs when the interpreter encounters invalid syntax, such as missing colons, unmatched parentheses, incorrect indentation, or invalid keywords.
Since this error happens during the code compilation stage (before execution), it cannot be caught using a regular try-except block.
To handle it, you must wrap the faulty code inside the exec() or compile() functions within a try-except block.
Here, we are demonstarting the occurence of SyntaxError and handling it using the following methods -
- exec() Method
- compile() Method
- Using a custom function with exception handling
Handling SyntaxError Using exec() Function
The exec() function is used to execute Python code dynamically. If the code contains a syntax error, it can be caught using a try-except block.
Example
In the following example, we use the exec() function to execute a string with invalid Python syntax. The resulting SyntaxError is caught and handled using a try-except block -
try: exec("x === 5") except SyntaxError: print("SyntaxError caught: Invalid syntax in the code.")
The output for the above code is shown below -
SyntaxError caught: Invalid syntax in the code.
Handling SyntaxError Using compile() Function
The compile() function converts a string of Python code into a code object, which can then be executed using the exec() function. If the syntax in the string is invalid, a SyntaxError is raised during the compilation stage and can be caught using a try-except block.
Example
In this example, the compile() function is used to check syntax errors before executing the code -
code = "def func print('Hello')" try: compiled = compile(code, "<string>", "exec") exec(compiled) except SyntaxError: print("SyntaxError caught: Compilation failed.")
We get the output as shown below -
SyntaxError caught: Compilation failed.
Creating a Custom Function for SyntaxError Handling
You can create a custom function to run Python code and automatically catch SyntaxError. This is helpful when you are building applications like code editors, interpreters, or tools that let users type in Python code.
The custom SyntaxError function makes sure that your program doesn't crash and can show a helpful error message.
Example
In this example, we define a function that accepts a string as input and tries to execute it using the exec() function. If there is a SyntaxError, it will be caught and a respective message will be displayed preventing the program from ending abruptly -
def run_code(code_str): try: exec(code_str) except SyntaxError as e: print("SyntaxError caught:", e) # testing with invalid code run_code("if True print('Yes')")
Following is the output obtained -
SyntaxError caught: expected ':' (<string>, line 1)
Why You Can't Catch SyntaxError Normally
Unlike most exceptions, a SyntaxError occurs during the compilation phase, before the code is actually executed. If the program contains a syntax error, Python will not run it at all.
Therefore, to catch a SyntaxError, we need to pass the code as a string to functions like exec() or compile().