Types of Exceptions in Java & Their Differences
In Java, exceptions are categorized based on their recoverability and handling requirements. The main types are:
- Checked Exceptions (Compile-time exceptions)
- Unchecked Exceptions (Runtime exceptions)
- Errors (Serious system-level issues)
1. Checked Exceptions (Must Be Handled)
✅ Definition:
Checked exceptions are forced by the compiler to be either caught (try-catch
) or declared (throws
) in the method signature. They represent expected failures that a programmer should handle.
✅ Characteristics:
- Occur due to external factors (files, databases, network, etc.).
- Must be handled (otherwise, the code won’t compile).
- Extends
Exception
(but notRuntimeException
).
✅ Examples:
Exception | When It Occurs |
---|---|
IOException | File or network issues |
FileNotFoundException | File is missing |
SQLException | Database errors |
InterruptedException | Thread is interrupted |
ClassNotFoundException | Class is not found at runtime |
✅ Example: Handling Checked Exceptions
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("test.txt"); // May throw FileNotFoundException
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
2. Unchecked Exceptions (Runtime Exceptions)
🚀 Definition:
Unchecked exceptions occur due to programming mistakes and are not forced to be handled by the compiler.
🚀 Characteristics:
- Caused by logic errors in the program.
- Extends
RuntimeException
. - No need for
try-catch
, but should be prevented with better coding.
🚀 Examples:
Exception | When It Occurs |
---|---|
NullPointerException | Accessing a null reference |
ArrayIndexOutOfBoundsException | Accessing an invalid array index |
ArithmeticException | Division by zero |
IllegalArgumentException | Passing invalid method arguments |
ClassCastException | Incorrect object casting |
🚀 Example: Unchecked Exception
public class UncheckedExceptionExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // Throws NullPointerException
}
}
🛠 How to prevent?
✅ Use if
checks before accessing objects:
if (str != null) {
System.out.println(str.length());
} else {
System.out.println("String is null!");
}
3. Errors (System-Level Failures)
💀 Definition:
Errors are serious JVM-level failures that should not be caught in the program.
💀 Characteristics:
- Caused by system failures (memory issues, JVM errors).
- Extends
Error
(notException
). - Should NOT be handled—indicates fatal conditions.
💀 Examples:
Error | When It Occurs |
---|---|
StackOverflowError | Infinite recursion |
OutOfMemoryError | JVM runs out of memory |
VirtualMachineError | JVM crashes |
AssertionError | Failed assert statement |
💀 Example: StackOverflowError
(Infinite Recursion)
public class StackOverflowExample {
public static void recursiveMethod() {
recursiveMethod(); // Infinite recursion!
}
public static void main(String[] args) {
recursiveMethod(); // Causes StackOverflowError
}
}
⚠️ Solution: Avoid infinite recursion by adding a base case.
4. Summary Table
Type | Inherits | Compiler Forces Handling? | When to Use |
---|---|---|---|
Checked Exception | Exception | ✅ Yes | Handle recoverable failures (I/O, DB, network) |
Unchecked Exception | RuntimeException | ❌ No | Fix logic errors in code (null access, bad indexing) |
Error | Error | 🚫 No | JVM-level failures (out of memory, recursion) |
5. Custom Exception Example
You can create your own exception by extending Exception
(for checked exceptions) or RuntimeException
(for unchecked exceptions).
Custom Checked Exception
class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new CustomCheckedException("Custom checked exception occurred");
} catch (CustomCheckedException e) {
System.out.println("Handled: " + e.getMessage());
}
}
}
Custom Unchecked Exception
class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message) {
super(message);
}
}
public class CustomRuntimeExceptionExample {
public static void main(String[] args) {
throw new CustomUncheckedException("This is an unchecked exception");
}
}
Final Thoughts
✔ Use checked exceptions for recoverable failures (I/O, network, DB).
✔ Use unchecked exceptions for programming mistakes (null references, bad indexes).
✔ Errors should not be caught—fix the underlying system issue instead.
✔ Use meaningful exception messages for better debugging.