Types of Error in Java



This content originally appeared on DEV Community and was authored by Bhuvana Sri R

In Java, errors are problems that occur during the execution or compilation of a program. They can be broadly categorized into three main types:

  1. Compile-time Errors

These errors occur when you try to compile the program — before it runs.
They are usually syntax or semantic errors detected by the Java compiler (javac).

Examples:

  • Missing semicolon (;)
  • Using an undeclared variable
  • Misspelling a keyword
  • Type mismatch

Example Code:

public class Example {
    public static void main(String[] args) {
        int a = 5
        System.out.println(a);
    }
}

Error: Missing semicolon (;) → Compile-time error

  1. Runtime Errors
  • These occur while the program is running, after successful compilation.
  • They cause the program to crash or behave unexpectedly.

Examples:

  • Dividing by zero → ArithmeticException
  • Accessing invalid array index → ArrayIndexOutOfBoundsException
  • Null object access → NullPointerException
  • File not found → FileNotFoundException

Example Code:

public class Example {
    public static void main(String[] args) {
        int a = 10 / 0;
        System.out.println(a);
    }
}

Error: ArithmeticException: / by zero → Runtime error

  1. Logical Errors
  • These occur when the program runs successfully but produces the wrong output.
  • The compiler and runtime won’t catch them — they are human mistakes in logic.

Examples:

  • Using the wrong formula
  • Incorrect loop conditions
  • Wrong variable used in calculation

Example Code:

public class Example {
    public static void main(String[] args) {
        int a = 10, b = 5;
        System.out.println("Sum = " + (a - b)); // Logical mistake
    }
}

Output: Sum = 5 → Incorrect result due to logic error


This content originally appeared on DEV Community and was authored by Bhuvana Sri R