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:
✔ 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:
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:
✔ 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.
🧰 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):
🎯 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 |
