What are the exceptions in Java? Checked and unchecked.
sobes.tech AI
Answer from AI
In Java, exceptions are divided into two main categories:
-
Checked exceptions — these are exceptions that are checked by the compiler at compile time. A method that can throw them must declare them in its signature using the
throwskeyword, and the calling code must handle them either throughtry-catchor by propagating them further.Example:
IOException,SQLException. -
Unchecked exceptions — these are runtime exceptions that do not require mandatory handling or declaration. They inherit from
RuntimeException.Example:
NullPointerException,IllegalArgumentException.
This division helps explicitly indicate errors that can and should be handled, and errors that usually indicate programming mistakes and do not require mandatory handling.
Example:
public void readFile(String path) throws IOException {
// Checked exception
FileReader file = new FileReader(path);
}
public void processData(Object data) {
if (data == null) {
throw new NullPointerException("Data cannot be null"); // Unchecked
}
}