Sobes.tech
Junior — Middle

What is the difference between unchecked and checked exceptions in Java?

sobes.tech AI

Answer from AI

In Java, checked exceptions are exceptions that are checked by the compiler during compilation. Methods that can throw them are required to declare this with throws, and the calling code must either handle these exceptions or also declare them.

Unchecked exceptions (RuntimeException and its subclasses) do not require mandatory handling or declaration. They are usually related to programming errors, such as NullPointerException or ArrayIndexOutOfBoundsException.

Example:

// Checked exception
public void readFile() throws IOException {
    // file reading code
}

// Unchecked exception
public void divide(int a, int b) {
    int result = a / b; // may throw ArithmeticException
}

Thus, checked exceptions are intended for situations that can be foreseen and handled, while unchecked are for errors that usually indicate bugs.

What is the difference between unchecked and checked… - sobes.tech