Sobes.tech
Junior — Middle

Are exception elements in Java checked or unchecked types?

sobes.tech AI

Answer from AI

In Java, exceptions are divided into checked and unchecked types.

  • Checked exceptions are subclasses of Exception, except for RuntimeException and its subclasses. The compiler requires such exceptions to be either handled in a try-catch block or declared in the method signature with throws.

  • Unchecked exceptions are RuntimeException and its subclasses, as well as Error. They do not require mandatory handling or declaration.

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, exception elements in Java can be either checked or unchecked types, depending on their hierarchy.