Skip to main content

Chapter 3b - Errors

Syntax error: Syntax errors are mistakes that a developer/user can do while writing the code. Examples of syntax errors are missing commas, quotes or spelling errors.

Example Syntax Error​

System.out.print(" I Love Java ");// This line is correct
system.out.print(" I Love Java ");//Syntax Error as 's' of "system" is in lowercase.

Logical Error: A logical error is a bug in a program that causes it to produce wrong or unintended result. However, the program compiles and runs without showing an error on the console.

Example Logical Error​

class Main {
public static void main(String args[]){
int a = 20;
int b = 0;
int result=a/b;// it is logical error as program will compile and throw
} // error at runtime i.e. java.lang.ArithmeticException: / by zero
}


Mini quiz β€” spot the error type​

Quiz

Syntax vs logical errors

1 / 3

System.out.println("Hi") (missing the closing semicolon) is an example of a

Pick an answer to see if you are right.


Chapter summary​

Key takeaways
  1. A syntax error breaks Java's grammar rules (missing semicolons, wrong capitalization, mismatched braces) β€” the compiler catches these before your program ever runs.
  2. A logical error compiles and runs fine, but produces the wrong answer β€” these are the hardest to catch because Java gives you no error message.
  3. Some logical mistakes (like dividing by zero) surface as a runtime exception, which at least tells you where things went wrong, even though the compiler could not catch it in advance.
  4. Reading the exact wording of a compiler error (and the line number it points to) is the fastest way to fix a syntax error.

Exercises​

Activity: Fix the syntax error

The starter code below is missing a semicolon. Fix it so it compiles and prints Ready.