Sobes.tech
Junior — Middle

Explain the differences 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 the compiler requires to be explicitly handled. They inherit from the Exception class but not from RuntimeException. Examples: IOException, SQLException. When calling a method that might throw a checked exception, you must either handle it in a try-catch block or declare it in throws.

  • Unchecked exceptions inherit from RuntimeException. The compiler does not require them to be explicitly handled. Examples: NullPointerException, IllegalArgumentException. They usually occur due to programming errors and should not be explicitly handled.

Example:

try {
    FileInputStream fis = new FileInputStream("file.txt"); // IOException - checked
} catch (IOException e) {
    e.printStackTrace();
}

int a = 5 / 0; // ArithmeticException - unchecked

Thus, checked exceptions require explicit handling, while unchecked ones do not.

Explain the differences between checked and unchecked… - sobes.tech