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 ErrorWhen It OccursExample
Syntax / Compile-Time ErrorWhile compiling codeMissing semicolon
Runtime Error (Exception)While running programDividing by zero
Logical ErrorProgram runs, but output is wrongWrong 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 TypeReason
ArithmeticExceptionDivide by zero
NullPointerExceptionAccessing an object that is null
ArrayIndexOutOfBoundsExceptionInvalid array index
NumberFormatExceptionConverting 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)

FeatureErrorException
Occurs due toSystem failureCode issues / invalid input
Recoverable?❌ No✔ Yes (try-catch)
ExamplesOutOfMemoryError, StackOverflowErrorNullPointerException, ArithmeticException

🧨 Example: Unchecked vs Checked Exception

TypeDescriptionExample
Unchecked ExceptionHappens at runtimeDivision by zero
Checked ExceptionMust be handled using try-catchFile 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 PointMeaning
Compile-Time ErrorsErrors while writing code
Runtime ErrorsErrors while running code
Logical ErrorsWrong output due to wrong logic
ExceptionsRecoverable errors
ErrorsSystem-level, not recoverable

You may also like...