Sobes.tech
Junior — Middle

Can you explain the difference between exceptions that require mandatory handling during compilation and exceptions that occur at runtime?

sobes.tech AI

Answer from AI

In Java, there are two types of exceptions: checked and unchecked.

  • Checked exceptions require mandatory handling during compilation. This means that if a method can throw such an exception, it must be either caught in a try-catch block or declared in the method signature with throws. Example: IOException.

  • Unchecked exceptions occur at runtime and do not require mandatory handling by the compiler. These are usually programming errors, such as NullPointerException or ArithmeticException.

Example:

public void readFile() throws IOException {
    // code that may throw IOException
}

public void process() {
    try {
        readFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Can you explain the difference between exceptions… - sobes.tech