How to 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 demonstrating the occurrence of SyntaxError and handling it using the following methods ?

  • exec() Method
  • compile() Method
  • Using a custom function with exception handling

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().

Using exec() Function

The exec() function executes Python code dynamically. If the code contains a syntax error, it can be caught using a try-except block ?

try:
    exec("x === 5")  # Invalid syntax: triple equals
except SyntaxError as e:
    print("SyntaxError caught:", e)
SyntaxError caught: invalid syntax (<string>, line 1)

Using compile() Function

The compile() function converts a string of Python code into a code object. If the syntax is invalid, a SyntaxError is raised during compilation ?

code = "def func print('Hello')"  # Missing colon
try:
    compiled = compile(code, "<string>", "exec")
    exec(compiled)
except SyntaxError as e:
    print("SyntaxError caught:", e)
SyntaxError caught: invalid syntax (<string>, line 1)

Creating a Custom Function for Error Handling

You can create a custom function to safely execute Python code and handle syntax errors. This is useful for applications like code editors or interpreters ?

def safe_exec(code_str):
    try:
        exec(code_str)
        print("Code executed successfully!")
    except SyntaxError as e:
        print(f"SyntaxError: {e}")
    except Exception as e:
        print(f"Runtime Error: {e}")

# Test with invalid syntax
safe_exec("if True print('Yes')")  # Missing colon

# Test with valid syntax
safe_exec("print('Hello World')")
SyntaxError: invalid syntax (<string>, line 1)
Code executed successfully!
Hello World

Comparison of Methods

Method Use Case When to Use
exec() Direct execution with error handling Simple dynamic code execution
compile() Check syntax before execution When you need to validate code first
Custom function Comprehensive error handling Production applications and tools

Conclusion

SyntaxError cannot be caught normally since it occurs at compilation time. Use exec() or compile() within try-except blocks to handle dynamic code with potential syntax errors safely.

Updated on: 2026-03-24T16:24:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements