What is the output?
public class Test {
public static void main(String[] args) {
int x = 0;
try {
x = 5;
System.out.println(x / 0);
x = 10;
} catch (ArithmeticException e) {
x = 15;
} finally {
System.out.println(x);
}
}
}
A5
B10
C15
DCompilation error
Correct Answer:
C. 15
EXPLANATION
x becomes 5, then ArithmeticException occurs. x becomes 15 in catch block. Finally block prints 15.
Consider the code:
try (FileReader fr = new FileReader("file.txt")) {
// use fr
} catch (IOException e) {
// handle
}
What will happen to 'fr' after the try block?
AIt remains open and must be manually closed
BIt is automatically closed
CIt causes a compilation error
DIt is closed only if exception occurs
Correct Answer:
B. It is automatically closed
EXPLANATION
Try-with-resources automatically closes resources implementing AutoCloseable interface, regardless of normal or exceptional termination.
Analyze the code:
public void process() throws IOException {
try {
readFile();
} catch (FileNotFoundException e) {
// handle
}
}
What is the issue here?
ANo issue, it's correct
BFileNotFoundException should not be caught
CIOException should also be caught as it's broader
Dthrows IOException is redundant
Correct Answer:
C. IOException should also be caught as it's broader
EXPLANATION
Since FileNotFoundException is a subclass of IOException, and readFile() can throw IOException, it should be caught in a separate catch block or the method signature should only throw FileNotFoundException.
What will be the output?
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");
}
}
}
AA C B
BA C
CA B C
DA
Correct Answer:
B. A C
EXPLANATION
After 'A' is printed, exception is thrown. Statement 'B' is never executed. Catch block prints 'C'.