Junior — Middle
Will a compilation error necessarily occur if a method has a throws declaration and the calling code does not handle it?
sobes.tech AI
Answer from AI
In Java, if a method declares a checked exception via throws, then the calling code must either handle this exception (try-catch) or also declare throws in its signature. If this is not done, a compilation error will occur.
However, if the method declares an unchecked exception (a subclass of RuntimeException), the compiler does not require mandatory handling, and there will be no compilation error.
Example:
public void method() throws IOException { }
public void caller() {
method(); // Compilation error if IOException is not handled
}
public void callerHandled() {
try {
method();
} catch (IOException e) {
e.printStackTrace();
}
}
Thus, a compilation error occurs only if a checked exception declared in throws is not handled.