Junior — Middle
What is the difference between checked and unchecked exceptions in Java?
sobes.tech AI
Answer from AI
In Java, exceptions are divided into checked and unchecked.
Checked exceptions are exceptions that inherit from the Exception class but not from RuntimeException. The compiler requires these exceptions to be either handled within a try-catch block or declared in the method signature with throws. This helps explicitly control potential errors that may occur during execution, such as IOException.
Unchecked exceptions are exceptions that inherit from RuntimeException. The compiler does not require them to be explicitly handled or declared. They are usually related to programming errors, such as NullPointerException or IllegalArgumentException.
Example:
public void readFile(String path) throws IOException { // checked exception
// file reading code
}
public void processData(Object data) {
if (data == null) {
throw new NullPointerException("Data is null"); // unchecked exception
}
}