Govt. Exams
Entrance Exams
public class Demo {
public static void main(String[] args) {
try {
System.out.println("A");
throw new Exception("Test");
System.out.println("B");
} catch (Exception e) {
System.out.println("C");
}
}
}
After 'A' is printed, exception is thrown. Statement 'B' is never executed. Catch block prints 'C'.
NumberFormatException is thrown by Integer.parseInt(), Double.parseDouble() when string format is invalid.
The correct order is try block executes first, then catch block (if exception occurs), and finally block always executes at the end.
public class Test {
public static void main(String[] args) {
try {
int[] arr = {1, 2};
System.out.println(arr[5]);
} catch (Exception e) {
System.out.println("Caught");
}
}
}
ArrayIndexOutOfBoundsException is caught by the generic Exception catch block, printing 'Caught'.
NumberFormatException is thrown when attempting to convert a string to a numeric type but the string does not have an appropriate format. It's an unchecked exception.
NullPointerException is thrown when attempting to call a method or access a property on a null object reference in Java.
Runnable is a functional interface, not related to exception hierarchy. Error and Exception are direct subclasses of Throwable. RuntimeException is a subclass of Exception.
A try block must be followed by either a catch block or a finally block (or both). A try block alone is not valid syntax.
IllegalArgumentException is thrown to indicate that a method has been passed an illegal or inappropriate argument. It is an unchecked exception.
IOException is a checked exception that must be caught or declared in the method signature. NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException are unchecked exceptions.