Sobes.tech
Senior

В чем разница между проверяемыми (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 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 forces the programmer to explicitly consider possible errors, such as IOException, 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 as NullPointerException, 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.