Java Errors

Java Errors

In Java, an error means something went wrong in the program. Errors may occur:

  • When writing code (compile-time error)

  • When running the program (runtime error)

  • Due to invalid logic (logical error)

Understanding errors is essential for debugging and writing clean code.


🧩 Types of Errors in Java

Type of Error When It Occurs Example
Syntax / Compile-Time Error While compiling code Missing semicolon
Runtime Error (Exception) While running program Dividing by zero
Logical Error Program runs, but output is wrong Wrong calculation

1️⃣ Syntax / Compile-Time Errors

These errors occur when code violates Java rules.

Examples:

public class Main {
public static void main(String[] args) {
System.out.println("Hello World") // Missing semicolon → Error
}
}

✔ The compiler will stop the program and show an error message.


2️⃣ Runtime Errors (Exceptions)

These errors appear while executing the program and stop the program unexpectedly.

Example:

public class Main {
public static void main(String[] args) {
int a = 10 / 0; // Arithmetic Exception
}
}

Common Runtime Errors:

Exception Type Reason
ArithmeticException Divide by zero
NullPointerException Accessing an object that is null
ArrayIndexOutOfBoundsException Invalid array index
NumberFormatException Converting invalid data to number

3️⃣ Logical Errors

The program runs successfully but gives incorrect results due to wrong logic.

Example:

public class Main {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println(a * b); // Should add but multiplied → logical error
}
}

✔ Hardest to detect because the program runs fine.


🛠 Handling Errors Using try-catch

Runtime errors can be handled using try-catch to prevent program crash.

public class Main {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}

🧰 Error vs Exception (Difference)

Feature Error Exception
Occurs due to System failure Code issues / invalid input
Recoverable? ❌ No ✔ Yes (try-catch)
Examples OutOfMemoryError, StackOverflowError NullPointerException, ArithmeticException

🧨 Example: Unchecked vs Checked Exception

Type Description Example
Unchecked Exception Happens at runtime Division by zero
Checked Exception Must be handled using try-catch File not found

Example (Checked Exception):

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File file = new File(“abc.txt”);
Scanner sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println(“File not found!”);
}
}
}


🎯 Summary

Key Point Meaning
Compile-Time Errors Errors while writing code
Runtime Errors Errors while running code
Logical Errors Wrong output due to wrong logic
Exceptions Recoverable errors
Errors System-level, not recoverable

You may also like...