Syntax Errors vs Runtime Exceptions

🏷️ Error Handling and Exceptions / What are Exceptions?

🧠 Context Introduction

When you start writing Python scripts, you will inevitably encounter errors. For engineers new to Python, understanding the two main categories of errors is essential. The first category is syntax errors, which prevent your code from running at all. The second category is runtime exceptions, which occur while your program is executing. Knowing the difference helps you debug faster and write more reliable code.


⚙️ What Are Syntax Errors?

Syntax errors are mistakes in the structure of your code. Python's interpreter cannot understand what you are trying to say because the code violates the rules of the language.

  • When do they occur? At the moment you try to run the script, before any code executes.
  • How do you spot them? Python will point to the exact line and often show a caret (^) indicating where the problem is.
  • Common causes:
  • Missing colons at the end of a def, if, for, or while statement.
  • Unmatched parentheses, brackets, or quotes.
  • Misspelled keywords (e.g., writing def as df).
  • Incorrect indentation (mixing tabs and spaces).

Example scenario: You write if x > 5 without a colon at the end. Python will immediately stop and tell you there is a syntax error on that line.


🛠️ What Are Runtime Exceptions?

Runtime exceptions (also called runtime errors) happen while your program is running. The syntax is correct, but something goes wrong during execution.

  • When do they occur? After the script starts running, when a specific operation fails.
  • How do you spot them? Python will print a traceback showing the sequence of function calls that led to the error.
  • Common causes:
  • Dividing by zero (ZeroDivisionError).
  • Trying to access a list index that does not exist (IndexError).
  • Using a variable that has not been defined (NameError).
  • Converting a string like "abc" to an integer (ValueError).

Example scenario: You have a list with three items, but your code tries to access the fifth item. The syntax is fine, but when the program runs, it crashes with an IndexError.


📊 Comparison Table: Syntax Errors vs Runtime Exceptions

Aspect Syntax Error Runtime Exception
When detected Before execution (compile time) During execution (runtime)
Does the program run? No, it never starts Yes, until the error occurs
Error message style Points to exact line with caret Shows traceback with line numbers
Common fix Correct the structure or punctuation Add checks, handle edge cases, or fix logic
Example Missing colon after if statement Dividing by zero inside a loop

🕵️ How to Identify Which One You Are Facing

  • If you see an error message immediately after pressing Run and the script does nothing else, it is likely a syntax error.
  • If your script starts running, prints some output, and then crashes with a traceback, you are dealing with a runtime exception.
  • Syntax errors are usually easier to fix because the interpreter tells you exactly where the problem is.
  • Runtime exceptions require you to think about the state of your data and the flow of your program.

✅ Quick Tips for Engineers

  • Read the error message carefully. Python is very descriptive. The first line often tells you the type of error.
  • For syntax errors: Look at the line indicated and the line immediately before it. Sometimes the mistake is on the previous line.
  • For runtime exceptions: Look at the last line of the traceback first. That is where the error actually happened.
  • Use a linter (like pylint or flake8) to catch syntax errors before you even run your code.
  • Use try-except blocks to handle runtime exceptions gracefully when you expect something might go wrong.

📝 Final Thought

As you write more Python scripts, you will encounter both types of errors regularly. Syntax errors are like grammar mistakes in a sentence — the reader cannot understand you. Runtime exceptions are like unexpected events during a conversation — the sentence was correct, but something went wrong in the delivery. Mastering the difference will make you a more confident and efficient Python programmer.


Syntax errors are mistakes in code structure that Python catches before running your program, while runtime exceptions occur during execution when something goes wrong.


🚫 Example 1: Missing colon after a function definition

This shows a syntax error where Python cannot parse the code because a required colon is missing.

def greet(name)
    print("Hello, " + name)

📤 Output: SyntaxError: invalid syntax


🚫 Example 2: Missing closing parenthesis

This demonstrates a syntax error caused by an unclosed parenthesis in a print statement.

print("Welcome to Python"

📤 Output: SyntaxError: unexpected EOF while parsing


⚡ Example 3: Dividing by zero (runtime exception)

This shows a runtime exception that occurs when the program tries to divide a number by zero during execution.

result = 10 / 0
print(result)

📤 Output: ZeroDivisionError: division by zero


⚡ Example 4: Accessing an undefined variable (runtime exception)

This demonstrates a runtime exception that happens when the code references a variable that has not been assigned a value.

total = price + tax
print(total)

📤 Output: NameError: name 'price' is not defined


⚡ Example 5: Converting invalid input to integer (runtime exception)

This shows a practical runtime exception that occurs when a user provides text that cannot be converted to a number.

user_input = "hello"
number = int(user_input)
print("Your number is:", number)

📤 Output: ValueError: invalid literal for int() with base 10: 'hello'


📊 Comparison Table: Syntax Errors vs Runtime Exceptions

Feature Syntax Error Runtime Exception
When detected Before program runs (at parse time) While program is executing
Code runs? No, Python refuses to start Yes, until the error occurs
Common causes Missing colons, parentheses, quotes Division by zero, invalid input, missing variables
Fix approach Correct the code structure Add error handling or fix the logic
Example message SyntaxError: invalid syntax ZeroDivisionError: division by zero

🧠 Context Introduction

When you start writing Python scripts, you will inevitably encounter errors. For engineers new to Python, understanding the two main categories of errors is essential. The first category is syntax errors, which prevent your code from running at all. The second category is runtime exceptions, which occur while your program is executing. Knowing the difference helps you debug faster and write more reliable code.


⚙️ What Are Syntax Errors?

Syntax errors are mistakes in the structure of your code. Python's interpreter cannot understand what you are trying to say because the code violates the rules of the language.

  • When do they occur? At the moment you try to run the script, before any code executes.
  • How do you spot them? Python will point to the exact line and often show a caret (^) indicating where the problem is.
  • Common causes:
  • Missing colons at the end of a def, if, for, or while statement.
  • Unmatched parentheses, brackets, or quotes.
  • Misspelled keywords (e.g., writing def as df).
  • Incorrect indentation (mixing tabs and spaces).

Example scenario: You write if x > 5 without a colon at the end. Python will immediately stop and tell you there is a syntax error on that line.


🛠️ What Are Runtime Exceptions?

Runtime exceptions (also called runtime errors) happen while your program is running. The syntax is correct, but something goes wrong during execution.

  • When do they occur? After the script starts running, when a specific operation fails.
  • How do you spot them? Python will print a traceback showing the sequence of function calls that led to the error.
  • Common causes:
  • Dividing by zero (ZeroDivisionError).
  • Trying to access a list index that does not exist (IndexError).
  • Using a variable that has not been defined (NameError).
  • Converting a string like "abc" to an integer (ValueError).

Example scenario: You have a list with three items, but your code tries to access the fifth item. The syntax is fine, but when the program runs, it crashes with an IndexError.


📊 Comparison Table: Syntax Errors vs Runtime Exceptions

Aspect Syntax Error Runtime Exception
When detected Before execution (compile time) During execution (runtime)
Does the program run? No, it never starts Yes, until the error occurs
Error message style Points to exact line with caret Shows traceback with line numbers
Common fix Correct the structure or punctuation Add checks, handle edge cases, or fix logic
Example Missing colon after if statement Dividing by zero inside a loop

🕵️ How to Identify Which One You Are Facing

  • If you see an error message immediately after pressing Run and the script does nothing else, it is likely a syntax error.
  • If your script starts running, prints some output, and then crashes with a traceback, you are dealing with a runtime exception.
  • Syntax errors are usually easier to fix because the interpreter tells you exactly where the problem is.
  • Runtime exceptions require you to think about the state of your data and the flow of your program.

✅ Quick Tips for Engineers

  • Read the error message carefully. Python is very descriptive. The first line often tells you the type of error.
  • For syntax errors: Look at the line indicated and the line immediately before it. Sometimes the mistake is on the previous line.
  • For runtime exceptions: Look at the last line of the traceback first. That is where the error actually happened.
  • Use a linter (like pylint or flake8) to catch syntax errors before you even run your code.
  • Use try-except blocks to handle runtime exceptions gracefully when you expect something might go wrong.

📝 Final Thought

As you write more Python scripts, you will encounter both types of errors regularly. Syntax errors are like grammar mistakes in a sentence — the reader cannot understand you. Runtime exceptions are like unexpected events during a conversation — the sentence was correct, but something went wrong in the delivery. Mastering the difference will make you a more confident and efficient Python programmer.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

Syntax errors are mistakes in code structure that Python catches before running your program, while runtime exceptions occur during execution when something goes wrong.


🚫 Example 1: Missing colon after a function definition

This shows a syntax error where Python cannot parse the code because a required colon is missing.

def greet(name)
    print("Hello, " + name)

📤 Output: SyntaxError: invalid syntax


🚫 Example 2: Missing closing parenthesis

This demonstrates a syntax error caused by an unclosed parenthesis in a print statement.

print("Welcome to Python"

📤 Output: SyntaxError: unexpected EOF while parsing


⚡ Example 3: Dividing by zero (runtime exception)

This shows a runtime exception that occurs when the program tries to divide a number by zero during execution.

result = 10 / 0
print(result)

📤 Output: ZeroDivisionError: division by zero


⚡ Example 4: Accessing an undefined variable (runtime exception)

This demonstrates a runtime exception that happens when the code references a variable that has not been assigned a value.

total = price + tax
print(total)

📤 Output: NameError: name 'price' is not defined


⚡ Example 5: Converting invalid input to integer (runtime exception)

This shows a practical runtime exception that occurs when a user provides text that cannot be converted to a number.

user_input = "hello"
number = int(user_input)
print("Your number is:", number)

📤 Output: ValueError: invalid literal for int() with base 10: 'hello'


📊 Comparison Table: Syntax Errors vs Runtime Exceptions

Feature Syntax Error Runtime Exception
When detected Before program runs (at parse time) While program is executing
Code runs? No, Python refuses to start Yes, until the error occurs
Common causes Missing colons, parentheses, quotes Division by zero, invalid input, missing variables
Fix approach Correct the code structure Add error handling or fix the logic
Example message SyntaxError: invalid syntax ZeroDivisionError: division by zero