Which of the following scenarios will NOT trigger a StackOverflowError?
AInfinite recursive function calls without base case
BVery deep try-catch nesting (theoretically)
CMutual recursion between multiple methods
DCreating too many local variables in a method
Correct Answer:
D. Creating too many local variables in a method
EXPLANATION
StackOverflowError occurs from stack overflow due to excessive method calls. Local variables contribute to stack but won't cause overflow like recursion.
What will be printed for this code?
public class ExceptionOrder {
public static void main(String[] args) {
try {
try {
throw new RuntimeException("Inner");
} catch (Exception e) {
throw new IOException("Outer");
}
} catch (IOException e) {
System.out.println("Caught IOException");
} catch (RuntimeException e) {
System.out.println("Caught RuntimeException");
}
}
}
ACaught IOException
BCaught RuntimeException
CCompilation error
DNo output
Correct Answer:
C. Compilation error
EXPLANATION
IOException is a checked exception and must be declared in method signature or caught. The inner catch throws IOException which isn't caught immediately.
What will be the result of executing this code?
public class MultiCatchTest {
public static void main(String[] args) {
try {
int[] arr = {1, 2};
int x = arr[5];
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Array or Null Error");
}
}
}
AArray or Null Error
BCompilation error - cannot use | in catch
CArrayIndexOutOfBoundsException thrown
DNo output - exception not caught
Correct Answer:
A. Array or Null Error
EXPLANATION
Multi-catch feature (Java 7+) allows handling multiple exceptions. ArrayIndexOutOfBoundsException is caught by the multi-catch block.
Correct Answer:
B. Exception class has constructor that accepts String message and Throwable cause
EXPLANATION
Exception class provides multiple constructors including one with String message and another with String message and Throwable cause for exception chaining.