Skip to content

Module 12 · Exception Handling — topic 2 of 11

Syntax errors versus runtime errors

The difference between errors Python finds before running code (SyntaxError, IndentationError) and errors that happen while code runs (exceptions), and how each is reported and fixed.

Beginner 8 min read·Lesson 184 of 306 in Python Programming

Learning objectives

  • Distinguish syntax errors from runtime errors
  • Read SyntaxError messages
  • Explain why runtime errors may appear only on some paths

Definition

A syntax error means the code breaks Python's grammar, so it cannot be compiled or run at all. A runtime error is an exception raised while valid code executes, often only for certain inputs.

Introduction

Some mistakes stop a program before its first line runs — a missing colon or bracket. Others hide until a particular input reaches a particular line. Telling them apart tells you how to fix them.

Why it matters

Syntax errors are fixed by correcting the code's shape; runtime errors need thinking about data and logic. Knowing which you face saves time.

Detailed explanation

Before running a file, Python compiles it to bytecode. If the grammar is wrong — unclosed brackets, missing colons, bad indentation — compilation fails with SyntaxError and nothing runs.

IndentationError (and its subclass TabError) are kinds of SyntaxError about inconsistent indentation.

Syntax error messages point to a file, line and position, and modern Python gives specific hints such as "expected ':'" or "'(' was never closed".

Runtime errors are exceptions raised while executing: NameError, TypeError, ZeroDivisionError and many more.

A runtime error only happens if the faulty line actually runs. A misspelled variable inside an if branch that is never taken goes unnoticed until that branch runs — which is why testing all paths matters.

Syntax errors in the file being run can't be caught by try/except in the same file, because the file never starts. They can be caught when compiling code dynamically, for example with compile() or when importing another module.

Logic errors are a third kind: the program runs without exceptions but produces the wrong answer. Only testing reveals those.

Syntax

Python
# Syntax error: the whole file refuses to run
if x > 1
print(x)
# Runtime error: only when this line executes
print(10 / count)
  • Syntax errors stop compilation.
  • Runtime errors happen during execution.
  • Logic errors give wrong results silently.

Code examples

Catching a syntax error while compiling

Python
code = "print('hi'"
try:
compile(code, "<demo>", "exec")
except SyntaxError as e:
print("SyntaxError:", e.msg, "on line", e.lineno)
Output
SyntaxError: '(' was never closed on line 1

A runtime error waits for its line

Python
def risky(flag):
if flag:
return undefined_name
return "fine"
print(risky(False))
try:
print(risky(True))
except NameError as e:
print("NameError:", e)
Output
fine
NameError: name 'undefined_name' is not defined

More examples

Checking snippets without running them

Python
snippets = {
"ok": "x = 1 + 2",
"missing colon": "if x > 1\n pass",
"bad indent": "x = 1\n y = 2",
"runtime only": "y = 1 / 0",
}
for label, src in snippets.items():
try:
compile(src, label, "exec")
print(f"{label:<14} compiles")
except SyntaxError as e:
print(f"{label:<14} {type(e).__name__}: {e.msg}")
Output
ok             compiles
missing colon  SyntaxError: expected ':'
bad indent     IndentationError: unexpected indent
runtime only   compiles

Step-by-step explanation

  • compile() checks grammar without executing anything.
  • IndentationError is reported by type, showing it is a special kind of SyntaxError.
  • 1 / 0 is grammatically fine, so it compiles; the error would only appear when it runs.

Expected output

Running “Checking snippets without running them” prints exactly:

TextOutput
ok compiles
missing colon SyntaxError: expected ':'
bad indent IndentationError: unexpected indent
runtime only compiles

Practical applications

  • Editors and linters highlight syntax errors as you type.
  • Test suites exercise rarely used branches to expose hidden runtime errors.

Best practices

  • Fix syntax errors first; they block everything else.
  • Use an editor with a linter.
  • Test every branch to flush out runtime errors.

Common mistakes

Trying to catch your own file's syntax error

Avoid

try:
if x > 1
pass
except SyntaxError:
pass

Prefer

Fix the grammar: if x > 1:

The file never compiles, so the try statement never runs.

Important notes

  • python -m py_compile file.py checks a file's syntax without running it.

Key takeaways

  • Syntax errors stop the program before it runs.
  • Runtime errors are exceptions on executed lines.
  • Logic errors produce wrong output without exceptions.

Try it yourself

  1. 1
    Write three broken one-liners and predict each SyntaxError message before compiling them.
  2. 2
    Find a hidden NameError by calling a function with arguments that reach every branch.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhich error can a try/except in the same file never catch?
Practise this topic