Code Error Fixes -- Syntax, Runtime & Logic Bugs
Code errors fall into three categories: syntax, runtime, and logic -- this guide shows you how to identify each type across Python, JavaScript, Go, and Rust with real error messages and fixes.
What You'll Learn
Why It Matters
Understanding the type of error you are looking at cuts debugging time in half. Syntax errors are caught by the compiler, runtime errors crash your program, and logic errors produce wrong results silently.
Real-World Use
When your Node server crashes with a TypeError or your Python script returns wrong calculations, knowing the error category tells you exactly where to look.
Common Code Errors Table
| Error Message | Type | Cause | Fix |
|---|---|---|---|
| SyntaxError: invalid syntax | Syntax | Missing colon, parenthesis, or quote | Add the missing token at the line indicated |
| TypeError: undefined is not a function | Runtime | Calling a method on undefined | Check object initialization before calling |
| IndexError: list index out of range | Runtime | Accessing index beyond list length | Validate list length before access |
| NullPointerException | Runtime | Dereferencing null object in Java | Add null checks before method calls |
| Off-by-one in loop condition | Logic | Loop runs too many or too few times | Change < to <= or vice versa |
Step-by-Step Fixes
Fix 1: Python SyntaxError
# bad.py
def hello(name)
print(f"Hello, {name}")
# fixed.py
def hello(name): # missing colon added
print(f"Hello, {name}")
Expected output:
Hello, World
Fix 2: JavaScript TypeError
// bad.js
const user = null;
console.log(user.name);
// fixed.js
const user = null;
if (user && user.name) {
console.log(user.name);
} else {
console.log("User or name is undefined");
}
Expected output:
User or name is undefined
Fix 3: Go Index Out of Range
// bad.go
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
fmt.Println(nums[5])
}
// fixed.go
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
if len(nums) > 5 {
fmt.Println(nums[5])
} else {
fmt.Println("Index out of range")
}
}
Expected output:
Index out of range
Fix 4: Rust Borrow Checker Error
// bad.rs
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &mut s;
println!("{}, {}", r1, r2);
}
// fixed.rs
fn main() {
let mut s = String::from("hello");
let r1 = &s;
println!("{}", r1);
let r2 = &mut s;
r2.push_str(" world");
println!("{}", r2);
}
Expected output:
hello
hello world
Fix 5: Python Off-by-One Logic Error
# bad.py
def sum_first_n(n):
total = 0
for i in range(n): # sums 0 to n-1
total += i
return total
print(sum_first_n(5)) # expects 15, gets 10
# fixed.py
def sum_first_n(n):
total = 0
for i in range(1, n + 1): # sums 1 to n
total += i
return total
print(sum_first_n(5)) # 1+2+3+4+5 = 15
Expected output:
15
Code Error Classification Flowchart
flowchart TD
A[Code Error Detected] --> B{When does it appear?}
B -->|Before execution| C[Syntax Error]
C --> D[Check line/column from traceback]
D --> E[Fix missing brackets, colons, quotes]
B -->|During execution| F{Runtime Error}
F --> G[Read exception type and message]
G --> H[Add guard clauses and validation]
B -->|Wrong output| I[Logic Error]
I --> J[Add print/logger at each step]
J --> K[Check loop bounds and conditionals]
E --> L[Code Working]
H --> L
K --> L
Prevention Tips
- Use a linter (flake8, ESLint, golangci-lint, clippy) to catch syntax errors before running
- Add type hints or static typing to catch runtime type errors early
- Write unit tests for edge cases including empty lists, null values, and boundary indices
- Use an IDE with real-time error highlighting to catch syntax errors as you type
- Review your logic with a rubber duck or pair programmer before writing complex loops
Practice Questions
What is the difference between a syntax error and a runtime error? Answer: A syntax error violates the language grammar and is caught by the compiler or interpreter before execution. A runtime error occurs during execution, like calling a method on null.
How do you debug a logic error that does not crash the program? Answer: Add print statements or use a debugger breakpoint to inspect variable values at each step and compare them to expected values.
What does an IndexError in Python indicate? Answer: You tried to access an element at an index that does not exist in the list, tuple, or string. Check that the index is within
range(len(sequence)).Why does Rust refuse to compile code with both immutable and mutable borrows active? Answer: To prevent data races at compile time. Rust's borrow checker ensures you either have one mutable reference or many immutable references, never both simultaneously.
Challenge: Write a Python function that safely divides two numbers and returns a custom error message for each possible error type (ZeroDivisionError, TypeError, ValueError). Answer:
def safe_divide(a, b): try: return a / b except ZeroDivisionError: return "Cannot divide by zero" except TypeError: return "Both arguments must be numbers" except ValueError: return "Invalid numeric value"
Quick Reference
| Error Type | Detection Method | Fix Strategy |
|---|---|---|
| Syntax | Compiler/interpreter error message | Fix at the exact line/column reported |
| Runtime | Exception/stack trace | Add conditionals and validation |
| Logic | Wrong output or behavior | Trace variable values step by step |
| Type | TypeError or type mismatch | Check function signatures and variable types |
| Off-by-one | Loop behaves one iteration off | Review loop bound with <= vs < |
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro