В чем разница между проверяемыми (checked) и непроверяемыми (unchecked) исключениями?
sobes.tech AI
Answer from AI
In Java, exceptions are divided into checked and unchecked based on how the compiler handles them.
-
Checked exceptions are exceptions that inherit from the
Exceptionclass but not fromRuntimeException. The compiler requires these exceptions to be either handled within atry-catchblock or declared in the method signature withthrows. This forces the programmer to explicitly consider possible errors, such asIOException,SQLException. -
Unchecked exceptions are exceptions that inherit from
RuntimeException. The compiler does not require them to be explicitly handled or declared. They usually indicate programming errors, such asNullPointerException,IllegalArgumentException.
Example:
public void readFile(String path) throws IOException { // checked
// file reading code that may throw IOException
}
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative"); // unchecked
}
}
Thus, checked exceptions require explicit handling, while unchecked exceptions signal logical errors that are usually not explicitly handled.