What will happen when the following code is executed?
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught");
}
ACompilation error
BRuntime error without output
CException caught
DNo output
Correct Answer:
C. Exception caught
EXPLANATION
Accessing arr[5] when array has only 3 elements throws ArrayIndexOutOfBoundsException which is caught and 'Exception caught' is printed.
Consider the following exception hierarchy. Which statement will compile without error?
class MyException extends Exception {}
class MyRuntimeException extends RuntimeException {}
Athrow new MyException();
Bint x = 10; x = x / 0; // No need to handle MyException
RuntimeException and its subclasses are unchecked, so they don't need to be caught or declared. Option A requires try-catch since MyException is checked.
What is the correct syntax for declaring a method that throws a checked exception?
Apublic void method() throws IOException {}
Bpublic void method() catch IOException {}
Cpublic void method() try IOException {}
Dpublic void method() exceptions IOException {}
Correct Answer:
A. public void method() throws IOException {}
EXPLANATION
The 'throws' keyword is used in method declaration to indicate that the method might throw checked exceptions. Syntax: method() throws ExceptionType {}
What will be the output?
try {
throw new Exception("Test");
} catch(Exception e) {
System.out.println("Caught");
throw new RuntimeException("New");
} finally {
System.out.println("Finally");
}
ACaught Finally followed by RuntimeException
BCaught RuntimeException Finally
CFinally Caught
DRuntimeException Caught Finally
Correct Answer:
A. Caught Finally followed by RuntimeException
EXPLANATION
The finally block executes after catch block. 'Caught' is printed, then finally block prints 'Finally', and then RuntimeException is thrown.
In multi-catch block (Java 7+), which operator is used to catch multiple exceptions in a single catch clause?
A&&
B||
C|
D&
Correct Answer:
C. |
EXPLANATION
Java 7 introduced multi-catch using the pipe (|) operator: catch(IOException | SQLException e). This allows handling multiple exception types in one block.
What is the output of the following code?
int x = 10;
try {
x = x / 0;
} catch (ArithmeticException e) {
x = 20;
} finally {
x = 30;
}
System.out.println(x);
A10
B20
C30
DError: compilation fails
Correct Answer:
C. 30
EXPLANATION
The finally block always executes last and sets x to 30. The output will be 30 because finally block assignments override catch block assignments.