Junior — Middle
Can exceptions occur that are checked at runtime, and how is this related to the exception handling mechanism in Java?
sobes.tech AI
Answer from AI
In Java, there are two types of exceptions: checked and unchecked. Exceptions that are checked during program execution are called unchecked exceptions (for example, NullPointerException, ArrayIndexOutOfBoundsException). They do not require mandatory catching or declaration in the method signature.
The exception handling mechanism in Java allows catching and handling both checked and unchecked exceptions using try-catch blocks. Checked exceptions require mandatory declaration or handling during compilation, while unchecked exceptions can occur during runtime and do not require mandatory handling, but they can be caught to prevent abrupt program termination.
Example of an unchecked exception:
public class Example {
public static void main(String[] args) {
String s = null;
try {
System.out.println(s.length()); // will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Handled exception: " + e);
}
}
}