- Syntax errors — mistakes in code structure
- Runtime errors — errors that occur during execution
- Logical errors — code runs but gives wrong results
- Exceptions — what they are and how they differ from errors
- Error vs Exception — the key differences
What's the Difference?
In Python programming, you'll encounter two types of problems: errors and exceptions. While they might seem similar, they are fundamentally different concepts.
The short answer is: errors are problems that stop your program from running, while exceptions are problems that can be handled during execution. But there's a lot more to it than that. Let's break it down.
💡 Key concept: Understanding the difference between errors and exceptions is the first step toward writing robust, error-free code.
Syntax Errors
Mistakes in Code Structure
Syntax errors occur when the code violates the rules of the Python language. These are also known as parsing errors. The interpreter detects them before the program starts running.
# Example 1: Missing colon
# if x > 5 # SyntaxError: expected ':'
# print("x is greater than 5")
# Example 2: Missing closing parenthesis
# print("Hello world" # SyntaxError: unexpected EOF while parsing
# Example 3: Incorrect indentation
# if True:
# print("This will cause an error") # IndentationError
# Example 4: Using a reserved keyword incorrectly
# class = "student" # SyntaxError: invalid syntax
Characteristics:
- Detected by the interpreter before execution
- Prevents the program from running
- Usually easy to fix
- Common examples: missing colons, parentheses, indentation
Quick Check: When does a syntax error occur? (Answer: Before the program runs, during parsing)
Runtime Errors
Errors During Execution
Runtime errors occur while the program is running. The syntax is correct, but something goes wrong during execution. These are also called exceptions.
# Example 1: Division by zero
# result = 10 / 0 # ZeroDivisionError
# Example 2: Accessing a non-existent index
# my_list = [1, 2, 3]
# print(my_list[5]) # IndexError
# Example 3: Accessing a non-existent key
# my_dict = {"a": 1, "b": 2}
# print(my_dict["c"]) # KeyError
# Example 4: Type error
# print("Hello" + 5) # TypeError
# Example 5: Name error
# print(undefined_variable) # NameError
Characteristics:
- Occurs during program execution
- Can be handled with try-except blocks
- Also known as exceptions
- Examples: division by zero, index out of range
Quick Check: What happens when a runtime error occurs? (Answer: The program stops execution unless the error is handled)
Logical Errors
Code Runs But Gives Wrong Results
Logical errors are the most difficult to find. The code runs without any error messages, but the output is incorrect. The program does what you told it to do, but not what you meant it to do.
# Example: Wrong calculation # def calculate_average(numbers): # total = sum(numbers) # return total / len(numbers) # If numbers is empty, this returns 0 # # data = [1, 2, 3, 4, 5] # print(calculate_average(data)) # 3.0 # # Better: Check for empty list # def calculate_average(numbers): # if not numbers: # return 0 # total = sum(numbers) # return total / len(numbers) # Example: Off-by-one error # numbers = [1, 2, 3, 4, 5] # for i in range(len(numbers)): # Works correctly # print(numbers[i]) # # Wrong: Forgetting to add the last element # for i in range(len(numbers) - 1): # This misses the last element # print(numbers[i])
Characteristics:
- No error messages — code runs fine
- Output is incorrect
- Hardest to find and fix
- Requires careful debugging
Quick Check: What is a logical error? (Answer: Code runs but gives incorrect results)
What are Exceptions?
Understanding Exceptions
An exception is a runtime error that can be handled by the program. Python provides a way to catch and respond to exceptions, allowing the program to continue running instead of crashing.
# Example: Handling division by zero
# try:
# result = 10 / 0
# except ZeroDivisionError:
# print("Cannot divide by zero!")
# # Example: Handling file not found
# try:
# with open("nonexistent.txt", "r") as file:
# content = file.read()
# except FileNotFoundError:
# print("File not found!")
# # Example: Handling multiple exceptions
# try:
# number = int(input("Enter a number: "))
# result = 10 / number
# except ValueError:
# print("That's not a valid number!")
# except ZeroDivisionError:
# print("Cannot divide by zero!")
Characteristics:
- Occurs during runtime
- Can be handled using try-except
- Prevents program crash
- Allows for graceful error recovery
Quick Check: What is the difference between an error and an exception? (Answer: Errors stop the program; exceptions can be handled)
Error vs Exception
Key Differences
While both errors and exceptions indicate problems in your code, they have fundamental differences:
# Comparison of Error vs Exception
# 1. Error (SyntaxError — can't be handled)
# print("Hello world" # SyntaxError: unexpected EOF while parsing
# 2. Exception (can be handled)
# try:
# 10 / 0
# except ZeroDivisionError:
# print("Caught the exception!")
# Summary Table:
# | Feature | Error | Exception |
# |---------|-------|-----------|
# | When occurs | At compile/parsing time | During runtime |
# | Can be handled? | No | Yes |
# | Stops program? | Yes, before running | Yes, unless handled |
# | Examples | SyntaxError, IndentationError | ZeroDivisionError, IndexError, TypeError
Key differences:
- Errors — occur at compile time, cannot be handled
- Exceptions — occur at runtime, can be handled
- Errors are fatal — program cannot run
- Exceptions are recoverable — program can continue
Quick Check: Can syntax errors be handled? (Answer: No — they stop the program from running)
Common Mistakes
Things to Watch Out For
Confusing Syntax Errors with Exceptions
# WRONG — trying to handle a syntax error
# try:
# print("Hello" # SyntaxError
# except SyntaxError: # This never runs because the code won't execute
# print("Handled!")
# CORRECT — fix the syntax error
print("Hello") # Valid syntax
Ignoring Exceptions
# WRONG — using a bare except
# try:
# result = 10 / 0
# except: # Catches everything, hides the problem
# pass
# CORRECT — handle specific exceptions
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Not Understanding the Error Message
# WRONG — ignoring the error message # Traceback (most recent call last): # File "", line 1, in # ZeroDivisionError: division by zero # # The error tells you exactly what went wrong! # CORRECT — read the error message and fix the issue # ZeroDivisionError means you divided by zero
Quick Check: What is the most common mistake with errors and exceptions? (Answer: Trying to handle syntax errors with try-except)
Try It Yourself
Experiment with errors and exceptions in the editor below. Modify the code and see what happens.
ERROR VS EXCEPTION PRACTICE
========================================
1. RUNTIME ERROR (DIVISION BY ZERO)
Caught ZeroDivisionError!
2. HANDLING MULTIPLE EXCEPTIONS
Caught ValueError!
3. LOGICAL ERROR
Average: 3.0
4. EXCEPTION HANDLING
Safe divide 10/2: 5.0
Safe divide 10/0: Cannot divide by zero!
Error vs Exception practice complete!
You've Got It!
You now understand the key differences between errors and exceptions — syntax errors, runtime errors, logical errors, and how exceptions can be handled. This is the foundation for exception handling!
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between an error and an exception?
Can I handle all types of errors?
What is the most common type of error in Python?
Why are logical errors hard to find?
What is the best way to learn about errors and exceptions?
What's a common interview question about errors and exceptions?
Where to Go From Here
Now that you understand errors and exceptions, check out these related topics:
Types of Exception
Learn about the different types of exceptions in Python.
Learn More →Exception Handling
Learn how to handle exceptions with try-except.
Learn More →User Defined Exception
Create your own custom exceptions.
Learn More →