1. Introduction
In Java, exceptions are categorized into two main types:
- Checked Exceptions
- Unchecked Exceptions
The key difference lies in when they are checked (compile-time vs runtime) and how they are handled.
2. Checked Exceptions
Explanation
- Checked exceptions are checked at compile-time.
-
The compiler forces you to handle them using:
-
try-catchblock OR -
throwskeyword
-
These exceptions represent recoverable conditions.
Common Examples
- IOException
- SQLException
- FileNotFoundException
Example
import java.io.FileReader;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("test.txt");
} catch (Exception e) {
System.out.println("File not found");
}
}
}
Explanation of Code
-
FileReadermay throwFileNotFoundException. - Compiler forces handling using
try-catch. - Without handling → compilation error.
3. Unchecked Exceptions
Explanation
- Unchecked exceptions are checked at runtime, not at compile-time.
- The compiler does NOT force you to handle them.
- They usually occur due to programming mistakes.
Common Examples
- NullPointerException
- ArithmeticException
- ArrayIndexOutOfBoundsException
Example
public class UncheckedExample {
public static void main(String[] args) {
int a = 10 / 0;
System.out.println(a);
}
}
Explanation of Code
- Division by zero causes
ArithmeticException. - Compiler allows it, but error occurs at runtime.
4. Key Differences Table
| Feature | Checked Exceptions | Unchecked Exceptions |
|---|---|---|
| Checked At | Compile-time | Runtime |
| Handling Required | Yes (Mandatory) | No (Optional) |
| Parent Class | Exception (excluding RuntimeException) | RuntimeException |
| Cause | External issues (I/O, DB) | Programming errors |
| Example | IOException | NullPointerException |
5. Code Comparison
// Checked Exception
import java.io.*;
class Test {
void readFile() throws IOException {
FileReader fr = new FileReader("abc.txt");
}
}
// Unchecked Exception
class Test2 {
void divide() {
int x = 10 / 0;
}
}
Explanation
-
readFile()must declarethrows IOException→ Checked -
divide()compiles fine but fails at runtime → Unchecked
6. When to Use What?
-
Use Checked Exceptions when:
- The error is recoverable
- You want the caller to handle it
-
Use Unchecked Exceptions when:
- The error is due to logic mistakes
- It cannot be reasonably recovered
7. Summary
- Checked Exceptions → Compile-time, must handle
- Unchecked Exceptions → Runtime, optional handling
- Checked = predictable & recoverable
- Unchecked = programming errors
Java Full Stack Developer Roadmap
To master exception handling and advanced Java concepts:
👉 https://www.ashokit.in/java-full-stack-developer-roadmap
Promotional Content
Want to master Java Exception Handling and crack interviews?
Top comments (0)