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 forRuntimeExceptionand its subclasses. The compiler requires such exceptions to be either handled in atry-catchblock or declared in the method signature withthrows. -
Unchecked exceptions are
RuntimeExceptionand its subclasses, as well asError. 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.