Junior — Middle
How to distinguish exceptions that need to be explicitly handled from those that can be omitted in the code?
sobes.tech AI
Answer from AI
In Java, exceptions are divided into checked and unchecked. Checked exceptions inherit from the class Exception but not from RuntimeException, and require mandatory handling — either through a try-catch block or by declaring in the method signature using the throws keyword. Unchecked exceptions inherit from RuntimeException and may not be explicitly declared — their handling is optional.
Example:
public void readFile() throws IOException { // IOException is a checked exception
// file reading code
}
public void parseInt(String s) {
int num = Integer.parseInt(s); // NumberFormatException is an unchecked exception
}
Thus, if the compiler requires you to handle or declare an exception in a method, it is a checked exception and must be explicitly handled.