Middle
What is the difference between Checked and Unchecked exceptions in Java? How to work with them?
sobes.tech AI
Answer from AI
In Java, exceptions are divided into Checked and Unchecked:
-
Checked exceptions are exceptions that are checked by the compiler at compile time. Methods that can throw them must declare this with
throws, and the calling code must either handle these exceptions (try-catch) or propagate them further. Examples:IOException,SQLException. -
Unchecked exceptions are subclasses of
RuntimeExceptionandError. The compiler does not require their handling or declaration. They are usually related to programming errors, such asNullPointerException,IllegalArgumentException.
How to work:
- Checked exceptions need to be explicitly handled or declared, which makes the developer think about possible errors and their handling.
- Unchecked exceptions usually indicate logical errors that are better fixed than caught.
Example:
public void readFile(String path) throws IOException {
FileReader fr = new FileReader(path); // IOException — checked
}
public void process(int[] arr) {
int x = arr[10]; // may throw ArrayIndexOutOfBoundsException — unchecked
}
Thus, Checked exceptions require explicit control, while Unchecked signal critical errors that are better prevented.